前面我們談過 JavaScript 的 call 方法,這次就來看看與 call 相似的 apply 方法。
apply vs call
兩者的差異在於:傳入的是參數本身,還是參數陣列。
這是 call 的用法:
復制代碼 代碼如下:
theFunction.call(valueForThis, arg1, arg2, ...)
而這是 apply:
復制代碼 代碼如下:
theFunction.apply(valueForThis, arrayOfArgs)
因此:
復制代碼 代碼如下:
arrayOfArgs = [arg1, arg2, ...];
JavaScript apply 方法
先看看先前 call 的用法:
復制代碼 代碼如下:
function print(p1, p2) {
console.log( p1 + ' ' + p2);
}
print.call(undefined, "Hello", "World");
由上面的敘述可以推得,當
復制代碼 代碼如下:
args = "Hello", "World";
function print(p1, p2) {
console.log( p1 + ' ' + p2);
}
print.call(undefined, args);
兩者其實是等價的,輸出結果同樣是 "Hello World"。差別在於 apply 接受的是一個參數陣列,能更便利地與可變參數場景搭配使用。