使用call
和apply
来调用一个函数有什么区别?
var func = function() {
alert('hello!');
};
func.apply();
vs func.call();
.
上述两种方法之间是否存在性能差异?什么时候使用call
比apply
更好,反之亦然?
不同的是,apply
允许你用arguments
作为数组来调用函数;call
要求明确列出参数。一个有用的记忆法是"A代表array,C代表comma."
伪语法。
`theFunction.apply(valueForThis, arrayOfArgs)'。
theFunction.call(valueForThis, arg1, arg2, ...)
。
从ES6开始,也有可能spread
将数组用于call
函数,你可以看到兼容性这里。
示例代码。
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.斯科特-艾伦对此事有[一篇不错的文章](http://odetocode.com/blogs/scott/archive/2007/07/04/function-apply-and-function-call-in-javascript.aspx)。
基本上,它们在处理函数参数的方式上有所不同。
apply()方法与call()相同,只是apply()需要一个数组作为第二个参数。这个数组代表了目标方法的参数。
所以。
// assuming you have f
function f(message) { ... }
f.call(receiver, "test");
f.apply(receiver, ["test"]);
回答关于何时使用每个函数的部分,如果你不知道你将传递的参数数量,或者如果它们已经在一个数组或类似数组的对象中(像arguments
对象来转发你自己的参数),使用apply
。否则就使用call
,因为没有必要将参数包在一个数组中。
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
当我没有传递任何参数时(如你的例子),我更喜欢call
,因为我在调用函数。apply
意味着你在应用函数到(不存在的)参数。
应该不会有任何性能上的差异,除非你使用apply
并将参数包在一个数组中(例如f.apply(thisObject, [a, b, c])
而不是f.call(thisObject, a, b, c)
)。我没有测试过,所以可能会有差异,但这将是非常具体的浏览器。如果你没有把参数放在数组中,call'可能更快,如果你有的话,
apply'则更快。