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