15.3.4.3 Function.prototype.apply(thisArg, argArray)

2010-07-04

mixed Function.prototype.apply(thisArg, argArray) throws TypeError

Invoke a function with a custom explicitly passed on this value and all the arguments to be applied as a single array. It will map the elements in argArray and pass them on as if the function was called with every element as an argument, in order. See also Function.prototype.call, which does the same thing except it maps the additional parameters instead of accepting one array.

Function.prototype.apply.length = 2

Note that thisArg is not changed in this function. In ES3 it was set to global if undefined or null or ran through ToObject for all other values. So in ES5 you can call and apply to any value as this.

Code: (Meta Ecma)
Function.prototype.apply = function(thisArg, argArray){
if (!IsCallable(this)) throw TypeError;
if (argArray === null || argArray === undefined) return this.[[Call]](thisArg, []);
if (!IsObject(argArray)) throw TypeError;
var len = argArray.[[Get]]("length");
if (len === undefined || len === null) throw TypeError;
var n = ToUint32(len);
if (n !== ToNumber(len)) throw TypeError;
var argList = [];
var index = 0;
while (index < n) {
var indexName = ToString(index);
var nextArg = argArray.[[Get]](indexName);
argList.push(netArg);
++index;
}
return this.[[Call]](thisArg, argList);
}