使用call
和apply
呼叫函式有什麼區別?
var func = function() {
alert('hello!');
};
func.apply();
vs func.call();
上述兩種方法之間是否存在效能差異?何時最好使用call
超過apply
,反之亦然?
使用call
和apply
呼叫函式有什麼區別?
var func = function() {
alert('hello!');
};
func.apply();
vs func.call();
上述兩種方法之間是否存在效能差異?何時最好使用call
超過apply
,反之亦然?
不同的是,apply
允許您以arguments
作為陣列呼叫函式;call
需要明確列出引數.有用的mnemonic是“用於陣列的A和用於逗號的C”.
偽語法:
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