使用 Function.prototype.apply()
和 Function.prototype.call()
调用函数有什么区别?
var func = function() {
alert('hello!');
};
func.apply();
vs func.call();
上述两种方法之间是否存在性能差异?什么时候最好使用 call
而不是 apply
,反之亦然?
最佳答案
不同的是,apply
允许您使用 arguments
作为数组来调用函数; call
需要明确列出参数。一个有用的助记符是 “A 表示 a 射线,C 表示 comma。”
伪语法:
theFunction.apply(valueForThis, arrayOfArgs)
theFunction.call(valueForThis, arg1, arg2, ...)
从 ES6 开始,还可以使用 spread
call
函数使用的数组,您可以查看兼容性 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
关于javascript - call 和 apply 和有什么不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1986896/