What is the difference between call and apply?

What is the difference between using call and apply to invoke a function?

var func = function(){
  alert('hello!');
};

func.apply();

vs

func.call();

Are there performance differences between the two methods? When is it best to use call over apply and vice versa?


The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is " A for a rray and C for c omma."

See MDN's documentation on apply and call.

Pseudo syntax:

theFunction.apply(valueForThis, arrayOfArgs)

theFunction.call(valueForThis, arg1, arg2, ...)

There is also, as of ES6, the possibility to spread the array for use with the call function, you can see the compatibilities here.

Sample code:

function theFunction(name, profession) {
    console.log("My name is " + name + " and I am a " + profession +".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator

K. Scott Allen has a nice writeup on the matter.

Basically, they differ on how they handle function arguments.

The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method."

So:

// assuming you have f
function f(message) { ... }
f.call(receiver, "test");
f.apply(receiver, ["test"]);

To answer the part about when to use each function, use apply if you don't know the number of arguments you will be passing, or if they are already in an array or array-like object (like the arguments object to forward your own arguments. Use call otherwise, since there's no need to wrap the arguments in an array.

f.call(thisObject, a, b, c); // Fixed number of arguments

f.apply(thisObject, arguments); // Forward this function's arguments

var args = [];
while (...) {
    args.push(some_value());
}
f.apply(thisObject, args); // Unknown number of arguments

When I'm not passing any arguments (like your example), I prefer call since I'm calling the function. apply would imply you are applying the function to the (non-existent) arguments.

There shouldn't be any performance differences, except maybe if you use apply and wrap the arguments in an array (eg f.apply(thisObject, [a, b, c]) instead of f.call(thisObject, a, b, c) ). I haven't tested it, so there could be differences, but it would be very browser specific. It's likely that call is faster if you don't already have the arguments in an array and apply is faster if you do.

链接地址: http://www.djcxy.com/p/380.html

上一篇: 我如何更新GitHub分叉库?

下一篇: 通话和申请有什么区别?