15.3.4.5 Function.prototype.bind(thisArg[, arg1[, arg2[, ..]]])

2010-07-04

function Function.prototype.bind(thisArg[, arg1[, arg2[, ..]]])

The bind function returns a (new special) function that does the same as this function. The only difference is that the this value (context) when executing the new function is always "bound" to a given value. Furthermore, this implementation allows you bind some or all of the parameters to a static value (arg1 ... argn).

Note that the returned function is a special function with certain special properties. Furthermore it has no [[Construct]] property, so it cannot be used in a new expression.

Function.prototype.bind.length = 1

Code: (Meta Ecma)
Function.prototype.bind = function(){
var Target = this;
if (!IsCallable(Target)) throw TypeError;
var A = Array.prototype.slice.call(arguments);
var thisArg = A.shift();
var F = new Object;
// todo: set all internal methods as 8.12 except for [[Get]]
F.[[Get]] = GetSpecialBindGetMethod(); // 15.3.5.4
F.[[TargetFunction]] = Target;
F.[[BoundThis]] = thisArg;
F.[[BoundArgs]] = A;
F.[[Class]] = "Function";
F.[[Prototype]] = Function.prototype; // 15.3.3.1
F.[[Call]] = GetSpecialBindCallMethod(); // 15.3.4.5.1
F.[[Construct]] = GetSpecialBindConstructor(); // 15.3.4.5.2
F.[[HasInstance]] = GetSpecialBindHasInstanceMethod(); // 15.3.4.5.3
if (Target.[[Class]] == "Function") {
var L = Target.length - A.length;
F.length = Math.max(0, L);
} else {
F.length = 0;
}
// set PD of F.length as specified in 15.3.5.1
F.[[Extensible]] = true;
var thrower = Object.[[ThrowTypeError]]; // 13.2.3
F.[[DefineOwnProperty]]("caller", PD{[[Get]]:thrower, [[Set]]:thrower, [[Enumerable]]:false, [[Configurable]]:false}, false);
F.[[DefineOwnProperty]]("arguments", PD{[[Get]]:thrower, [[Set]]:thrower, [[Enumerable]]:false, [[Configurable]]:false}, false);
}

Note that functions returned by bind do not have the internal [[Code]], [[FormalParameters]] or [[Scope]] properties. They also don't have a prototype property.