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
a closure that incorporates both the
getName() function and the "
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
Finally, a third alert is brought up via a
setTimeout() function and confirms
name is still in memory, long after the initial call to
getNameFunction() has finished executing, it is reasonable
to expect that the
name variable will have been deallocated. Since the
variable is still available to the
getName() function, this is obviously not
the case! The key to the name variable's persistence is that
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
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
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