Chapter 9. Fun with Functions
This chapter covers
- Understanding JavaScript functions
- Function context and closures in JavaScript
- Working with closures using Prototype
In chapter 8, we looked at the JavaScript Object type in some detail. Coming to it with the expectations of object-oriented programmers, we were surprised to see how little resemblance it bore to the objects of mainstream OO programming. In this chapter, we’re going to look at the JavaScript Function from a similar perspective.
Functions look a bit like class methods, but they are really quite different. As with the Object, Prototype extends the capabilities of the Function in quite elegant ways. The crown jewel of Prototype’s support for functions is its ability to make closures easier to work with. Closures are a somewhat obscure, but very powerful, feature of the JavaScript language. Understanding closures can be useful when writing any JavaScript code, but the event-driven style of programming used to handle mouse and keyboard events in JavaScript, and used by the XHR object (see chapters 3 and 4), require the use of closures. We’ll begin with a review of the Function object and closures as defined by the JavaScript language itself, and then move on to look at Prototype’s enhanced capabilities.
In keeping with the previous chapter, we’ll be dealing with a lot of low-level coding details, so we’ll work with the Scratchpad application that we introduced in chapter 8 to help us visualize the results.