Understanding JavaScript Closures | WebReference

Understanding JavaScript Closures

By Rob Gravelle


[next]

JavaScript closures are considered to be advanced stuff, reserved for the gurus of the field. A lot has been written about them, but mostly in the academic realm, with little or no attempt made to make the topic understandable to the non-scholar. That's really a shame, because closures are the answer to the problem of how to bind variables to functions that are called at a later time. Today's article will explain what closures are, outline some common dilemmas, and present ways that closures can be utilized to overcome them.

A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created. In the following example, the getNameFunction() forms a closure that incorporates both the getName() function and the "Rob" string that is local to the outer function's scope. When the code is executed, it displays an alert box that says "Hello Rob!". A second alert shows that the displayName variable now holds the getName() function, without the name variable. Finally, a third alert is brought up via a setTimeout() function and confirms that the name is still in memory, long after the initial call to getNameFunction():

Once getNameFunction() has finished executing, it is reasonable to expect that the name variable will have been deallocated. Since the name variable is still available to the getName() function, this is obviously not the case! The key to the name variable's persistence is that getNameFunction() has become a closure. The basic closure pattern can be put to good use by implementing two components, as follows:

  • A Function Factory:
    • Contains one or more local variables which are referenced by a local, inner function.
    • Returns the function and not the results of the function.
  • A Calling Function:
    • The Factory is called and its result (a function) is stored to a variable.
    • On subsequent calls, the calling function will hold a reference to the local variables, as they were when the closure was first created.

Practical Uses for the Closure Pattern

Overriding Functions

Here is a way to use a closure to override the document.createElement() function, so that we can add two additional parameters. Typically, we would have to store the original function so that we could use it in our own function:



Although there is nothing technically wrong with this approach, the creation of a global variable is awkward and perhaps even error-prone. A better way is to pass the original document.createElement() function to ours so that it will be retained in memory. That allows us to delegate the node creation to it. Rather than create a function that would only be called once, we can use an inline one to execute it immediately, and store the results in our overridden document.createElement() function:


[next]