Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Callbacks Functions can make it easier to deal with discontinuous events. For example, sup- pose there is a sequence that begins with a user interaction, making a request of the server, and finally displaying the server's response. The naïve way to write that would be: request = prepare_the_request( ); response = send_request_synchronously(request); display(response); The problem with this approach is that a synchronous request over the network will leave the client in a frozen state. If either the network or the server is slow, the degra- dation in responsiveness will be unacceptable. A better approach is to make an asynchronous request, providing a callback func- tion that will be invoked when the server's response is received. An asynchronous function returns immediately, so the client isn't blocked: request = prepare_the_request( ); send_request_asynchronously(request, function (response) { display(response); }); We pass a function parameter to the send_request_asynchronously function that will be called when the response is available. Module We can use functions and closure to make modules. A module is a function or object that presents an interface but that hides its state and implementation. By using func- tions to produce modules, we can almost completely eliminate our use of global vari- ables, thereby mitigating one of JavaScript's worst features. For example, suppose we want to augment String with a deentityify method. Its job is to look for HTML entities in a string and replace them with their equivalents. It makes sense to keep the names of the entities and their equivalents in an object. But where should we keep the object? We could put it in a global variable, but glo- bal variables are evil. We could define it in the function itself, but that has a runtime cost because the literal must be evaluated every time the function is invoked. The ideal approach is to put it in a closure, and perhaps provide an extra method that can add additional entities: String.method('deentityify', function ( ) { // The entity table. It maps entity names to // characters. var entity = { quot: '"', 40 | Chapter 4: Functions