问题描述
不同之处在于apply
,您可以将函数arguments
作为数组调用;call
要求明确列出参数。一个有用的助记符是 A代表数组,C代表逗号”。
伪语法:
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
解决方法
Function.prototype.apply()
使用和Function.prototype.call()
调用函数有什么区别?
var func = function() {
alert('hello!');
};
func.apply();` 对比 `func.call();
上述两种方法之间是否存在性能差异?什么时候最好使用call
over apply
,反之亦然?