78
Note that we save this method as
Function.prototype.bind
, so that all function objects
inherit it. This technique is explained in detail in §9.4.
Example 8-5. A Function.bind() method for ECMAScript 3
if (!Function.prototype.bind) {
Function.prototype.bind = function(o /*, args */) {
// Save the this and arguments values into variables so we can
// use them in the nested function below.
var self = this, boundArgs = arguments;
// The return value of the bind() method is a function
return function() {
// Build up an argument list, starting with any args passed
// to bind after the first one, and follow those with all args
// passed to this function.
var args = [], i;
for(i = 1; i < boundArgs.length; i++) args.push(boundArgs[i]);
for(i = 0; i < arguments.length; i++) args.push(arguments[i]);
// Now invoke self as a method of o, with those arguments
return self.apply(o, args);
};
};
}
Notice that the function returned by this
bind()
method is a closure that uses the var-
iables
self
and
boundArgs
declared in the outer function, even though that inner func-
tion has been returned from the outer function and is invoked after the outer function
has returned.
The
bind()
method defined by ECMAScript 5 does have some features that cannot be
simulated with the ECMAScript 3 code shown above. First, the true
bind()
method
returns a function object with its
length
property properly set to the arity of the bound
function minus the number of bound arguments (but not less than zero). Second, the
ECMAScript 5
bind()
method can be used for partial application of constructor func-
tions. If the function returned by
bind()
is used as a constructor, the
this
passed to
bind()
is ignored, and the original function is invoked as a constructor, with some
arguments already bound. Functions returned by the
bind()
method do not have a
prototype
property (the
prototype
property of regular functions cannot be deleted) and
objects created when these bound functions are used as constructors inherit from the
prototype
of the original, unbound constructor. Also, a bound constructor works just
like the unbound constructor for the purposes of the
instanceof
operator.
8.7.5 The toString() Method
Like all JavaScript objects, functions have a
toString()
method. The ECMAScript spec
requires this method to return a string that follows the syntax of the function declara-
tion statement. In practice most (but not all) implementations of this
toString()
meth-
od return the complete source code for the function. Built-in functions typically return
a string that includes something like “[native code]” as the function body.
8.7 Function Properties, Methods, and Constructor | 189
Core JavaScript