sam creasey
sam creasey

Reputation: 49

What is the difference between calling a function with call/apply or directly?

I know that by calling apply you have access to a different this property from within the function, but in this specific situation I have no idea why they would be any different. Wouldn't the 'this' be coming from the same place (item) regardless ?

This original code did not work:

_.invoke = function (collection, methodName) {

    var slicedArgs = Array.prototype.slice.call(arguments, 2);

    return _.map(collection, (item) => {
        if (typeof methodName === "string") {
            return item[methodName](slicedArgs);
        } else {
            return methodName.apply(item, slicedArgs);
        }
    });
};

And when I changed what was inside the map function it worked fine:

_.invoke = function (collection, methodName) {
    var slicedArgs = Array.prototype.slice.call(arguments, 2);

    return _.map(collection, (item) => {
        if (typeof methodName === "string") {
            return item[methodName].apply(item, slicedArgs);
        } else {
            return methodName.apply(item, slicedArgs);
        }
    });
};

So what's the deal with apply? What was the 'this' binding to in my first code, and what changed in the second?

Upvotes: 0

Views: 77

Answers (1)

CherryDT
CherryDT

Reputation: 29012

In the first example you were missing the ... to spread your slicedArgs array into several arguments, so you passed the array itself as a single argument. If you change your code to return item[methodName](...slicedArgs) it will work.

The reason it works with apply is that apply takes an array of arguments.

Upvotes: 1

Related Questions