HTML and CSS Reference
In-Depth Information
called, calls the original function with the bound object as the
this
value. In other
words, it provides the functionality we just implemented manually, and could be
considered the deferred companion to
call
and
apply
. Using
bind
, we could
update
anchorLightbox
as shown in Listing 6.3.
Listing 6.3
Using
bind
function anchorLightbox(anchor, options) {
/* ... */
anchor.onclick = lb.open.bind(lb);
/* ... */
}
Because not all browsers yet implement this highly useful function, we can
conditionally provide our own implementation for those browsers that lack it.
Listing 6.4 shows a simple implementation.
Listing 6.4
Implementation of
bind
if (!Function.prototype.bind) {
Function.prototype.bind = function (thisObj) {
var target = this;
return function () {
return target.apply(thisObj, arguments);
};
};
}
The implementation returns a function—a
closure
—that maintains its reference
to the
thisObj
argument and the function itself. When the returned function is
executed, the original function is called with
this
explicitly set to the bound object.
Any arguments passed to the returned function is passed on to the original function.
Adding the function to
Function.prototype
means it will be available
as a method on all function objects, so
this
refers to the function on which the
method is called. In order to access this value we need to store it in a local variable
in the outer function. As we saw in the previous chapter,
this
is calculated upon
entering a new execution context and is not part of the scope chain. Assigning it to
a local variable makes it accessible through the scope chain in the inner function.