call 和 apply 是 JavaScript 裡用來「借用」函式、改變 this 指向的兩個方法。兩者的第一個參數都是函式的母物件(呼叫上下文),在函式內部透過 this 取得它的參考。
如果想把函式 f 當成物件 o 的方法來呼叫,可以這樣寫:
f.call(o);
f.apply(o);
它的效果等同於以下三步驟:
o.m = f; //將f存儲為o的臨時方法
o.m(); //調用這個臨時方法
delete o.m; //將這個臨時方法刪除
function testFun(){
return this.a + this.b;
}
var o = {a:1, b:2};
testFun.call(o); //3
testFun.apply(o); //3
結果都是 3,可以理解成 return o.a + o.b。
var a = 10, b = 20;
function testFun(){
return this.a + this.b;
}
testFun.call();
testFun.apply();
結果會是 30。這是因為當 call/apply 的第一個參數傳入 null 或 undefined 時,會被全域物件取代。
關鍵差異在「後續參數的傳遞方式」。call 是把上下文之後的所有參數,逐一列在後面:
f.call(o, 1, 2);
而 apply 則是把上下文之後的參數打包成一個陣列傳入:
f.apply(o, [1, 2]);
用一個帶參數的例子對照:
function testFun(x, y){
return this.a + this.b + x + y;
}
var o = {a:1, b:2};
testFun.call(o, 10, 20);
testFun.apply(o, [10, 20]);
兩者結果都是 33,等同於 return o.a + o.b + 10 + 20。簡單記法:參數不多用 call,參數已是陣列時用 apply。