如果你習慣了編譯型語言的思維,第一次接觸 JavaScript 常會有種神奇又怪異的感覺:直覺上不可能發生的事偏偏發生了。這種困惑多半來自一件事——JavaScript 可以在執行期動態改變函式的運行上下文,而這項特性最集中的體現,就是 apply 與 call 這兩個方法。
語法:call(thisObj, Object)
定義:呼叫某個物件的方法,並以另一個物件取代目前的 this。
說明:call 可以把函式的物件上下文從原本的物件切換成 thisObj 指定的新物件。如果沒有提供 thisObj,Global 物件會被當成 thisObj。
語法:apply(thisObj, [argArray])
定義:套用某個物件的方法,同樣以另一個物件取代目前的 this。
說明:如果 argArray 不是有效陣列或 arguments 物件,會丟出 TypeError。若 thisObj 與 argArray 都未提供,Global 物件會被用作 thisObj,且無法傳入任何參數。
兩者功能完全一致,只是 call 直接接參數列表,apply 則把參數包成陣列傳入。
func.call(func1, var1, var2, var3); // 等價寫法 func.apply(func1, [var1, var2, var3]);
function Animal(name) {
this.name = name;
this.showName = function() {
console.log(this.name);
};
}
function Cat(name) {
Animal.call(this, name); // call 需逐一傳入參數
}
Cat.prototype = new Animal();
function Dog(name) {
Animal.apply(this, name); // apply 第二個參數需為陣列
}
Dog.prototype = new Animal();
var cat = new Cat("Black Cat");
var dog = new Dog(["Black Dog"]);
cat.showName();
dog.showName();
console.log(cat instanceof Animal);
console.log(dog instanceof Animal);
注意 Dog 那邊如果寫成 Animal.apply(this, "Black Dog"),字串會被當成類陣列逐字拆開,結果完全不是預期,這是最常見的誤用。
function Animal(name) {
this.name = name;
this.showName = function() {
alert(this.name);
};
}
function Cat(name) {
this.superClass = Animal;
this.superClass(name); // 以當前 this 呼叫父類
delete this.superClass;
}
var cat = new Cat("Black Cat");
cat.showName();
apply:套用某物件的方法,以另一物件取代目前的 this。參數最多兩個——新的 this 物件與一個陣列。即使只有一個參數也必須包進陣列;若 argArray 不是有效陣列或 arguments,會導致 TypeError。
call:呼叫某物件的方法,以另一物件取代目前的 this。接受的是直接的參數列表,主要用在物件方法互相呼叫時保持 this 指向一致,或需要刻意改變 this 指向的場景。
共同點:都能用來代替另一個物件呼叫方法,把函式的物件上下文從初始上下文改為 thisObj 指定的新物件。
選用建議很簡單:參數個數固定時用 call 更直觀;參數個數不確定、或手上本來就有一個陣列/arguments 時,用 apply 更省事。