HTML and CSS Reference
In-Depth Information
called as a property of it. In the previous chapter we saw how call and apply can
be used to explicitly set the this value when calling a function. However, those
methods only help at call time.
6.1.2 Fixing this via an Anonymous Function
To work around the problem, we could assign an anonymous function as the event
handler that when executed calls the open method, making sure the correct this
value is set. Listing 6.2 shows the workaround.
Listing 6.2 Calling open through an anonymous proxy function
function anchorLightbox(anchor, options) {
/* ... */
anchor.onclick = function () {
return lb.open();
};
/* ... */
}
Assigning the inner function as the event handler creates a closure . Normally,
when a function exits, the execution context along with its activation and variable
object are no longer referenced, and thus are available for garbage collection. How-
ever, the moment we assign the inner function as the event handler something in-
teresting happens. Even after the anchorLightbox finishes, the anchor object,
through its onclick property, still has access to the scope chain of the execution
context created for anchorLightbox . The anonymous inner function uses the
lb variable, which is neither a parameter nor a local variable; it is a free variable,
accessible through the scope chain.
Using the closure to handle the event, effectively proxying the method call, the
lightbox anchor should now work as expected. However, the manual wrapping of
the method call doesn't feel quite right. If we were to define several event handlers
in the same way, we would introduce duplication, which is error-prone and likely to
make code harder to maintain, change, and understand. A better solution is needed.
6.1.3 Function.prototype.bind
ECMAScript 5 provides the Function.prototype.bind function, which is
also found in some form in most modern JavaScript libraries. The bind method
accepts an object as its first argument and returns a function object that, when
 
Search WWH ::




Custom Search