HTML and CSS Reference
In-Depth Information
6
Applied Functions
and Closures
I n the previous chapter we discussed the theoretical aspects of JavaScript func-
tions, familiarizing ourselves with execution contexts and the scope chain. JavaScript
supports nested functions, which allows for closures that can keep private state, and
can be used for anything from ad hoc scopes to implementing memoization, function
binding, modules and stateful functions, and objects.
In this chapter we will work through several examples of how to make good
use of JavaScript functions and closures.
6.1 Binding Functions
When passing methods as callbacks, the implicit this value is lost unless the object
on which it should execute is passed along with it. This can be confusing unless the
semantics of this are familiar.
6.1.1 Losing this : A Lightbox Example
To illustrate the problem at hand, assume we have a “lightbox” object. A lightbox
is simply an HTML element that is overlaid the page, and appears to float above the
rest of the page, much like a popup, only with a web 2.0 name. In this example the
lightbox pulls content from a URL and displays it in a div element. For convenience,
an anchorLightbox function is provided, which turns an anchor element into a
93
 
 
Search WWH ::




Custom Search