Ad

How Does The JavaScript .apply Method Work?

- 1 answer

I'm not asking how to use it. I know how to use it.

But when apply invokes the function that called it, how exactly does it pass an array of arguments into a function that was not written to take an array for an argument? Does it combine its given arguments array with the called functions "arguments"?

I looked at the latest ECMAscript specifications for .apply and .call, but I didn't really see anything about underlying logic.

Any explanation would be welcome. I'm new to JavaScript, and want to better understand what's going on under the hood. I'm currently trying to recreate some of the basic functions on my own, and this one is giving me a lot of trouble.

Ad

Answer

From the spec.

We have to take the argArray and create what will be the arguments object pseudo array.

Essentially

Function.prototype.apply = function apply (thisArg, argArray) {
    var len = argArray.length;
    var n = ToUint32(len);
    var argList = []; // where this is a List not an array.
    var index = 0;
    var indexName;
    var nextArg;
    while (index < len) {
        indexName = ToString(index);
        nextArg = argArray[indexName];
        argList.push(nextArg);
        index++;
    }
    return this['[[Call]]'](func, thisArg, argList); // ignore the syntax however
                                                     // This is the line where the function
                                                     // will be called and provide 
                                                     // the thisArg and thisArray
}

I omitted some of the type checking that happens but this is essentially pretty close to what the spec dictates as how Function.prototype.apply is implemented. We craft our own object and build up the argList prior to calling the function.

Its important to note. that the internal method named [[Call]] is different than Function.prototype.call.

Ad
source: stackoverflow.com
Ad