问题描述
使用 Function.prototype.apply()
和 Function.prototype.call()
调用函数有什么区别?
What is the difference between using Function.prototype.apply()
and Function.prototype.call()
to invoke a function?
var func = function() {
alert('hello!');
};
func.apply();
vs func.call();
上述两种方法之间是否存在性能差异?什么时候最好使用 call
而不是 apply
,反之亦然?
Are there performance differences between the two aforementioned methods? When is it best to use call
over apply
and vice versa?
推荐答案
区别在于 apply
可以让你使用 arguments
作为数组来调用函数;call
需要明确列出参数.一个有用的助记符是A代表array,C代表comma."
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 array and C for comma."
See MDN's documentation on apply and call.
伪语法:
theFunction.apply(valueForThis, arrayOfArgs)
theFunction.call(valueForThis, arg1, arg2, ...)
从 ES6 开始,还有可能 spread
数组与call
函数一起使用,可以看到兼容性这里.
There is also, as of ES6, the possibility to spread
the array for use with the call
function, you can see the compatibilities here.
示例代码:
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
这篇关于call 和 apply 和有什么不一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!