call 與 apply 是每個 JavaScript 開發者都該弄懂的方法。它們的作用可以用一句話概括:借用別人的方法,並指定 this 是誰。理解之後,函式借用與原型繼承都會變得很自然。
call
fun.call(thisArg, arg1, arg2, ...)
以 thisArg 作為 this 來呼叫 fun,其餘參數逐一列舉。
apply
fun.apply(thisArg, [argsArray])
同樣以 thisArg 作為 this,但第二個參數必須是陣列(或類陣列物件如 arguments),會被展開成參數列表。
兩者唯一的差別就在參數的傳遞形式。若省略 thisArg,非嚴格模式下會退化為全域物件。
function add(a, b) { alert(a + b); }
function sub(a, b) { alert(a - b); }
add.call(sub, 3, 1); // 4
這裡的意思是「用 sub 作為 this 來執行 add」,因此結果等同 add(3, 1)。要理解這件事,得記住一個前提:JavaScript 中函式本身就是物件,函式名只是對 Function 實例的參照。
function Animal() {
this.name = "Animal";
this.showName = function() { alert(this.name); };
}
function Cat() { this.name = "Cat"; }
var animal = new Animal();
var cat = new Cat();
animal.showName.call(cat); // Cat
Cat 原本沒有 showName,透過 call 把 Animal 的方法拿來在 cat 身上執行,因此 this.name 讀到的是 Cat。
function Animal(name) {
this.name = name;
this.showName = function() { alert(this.name); };
}
function Cat(name) {
Animal.call(this, name); // 關鍵:把 Animal 的初始化套用到自己身上
}
var cat = new Cat("Black Cat");
cat.showName(); // Black Cat
Animal.call(this, name) 相當於在 Cat 的建構過程中先跑一遍 Animal,於是 Cat 的實例就擁有了 Animal 的所有屬性與方法。這種手法稱為偽古典繼承或「建構函式繼承」。
function Class10() {
this.showSub = function(a, b) { alert(a - b); };
}
function Class11() {
this.showAdd = function(a, b) { alert(a + b); };
}
function Class2() {
Class10.call(this);
Class11.call(this);
}
連續呼叫兩次,就把兩個父類別的能力都併了進來。
Array.prototype.slice.call(arguments),這是它最實用的場合之一。Math.max.apply(null, arr)(大量元素時請改用 Math.max(...arr) 或 reduce,避免參數數量爆掉)。Array.prototype.forEach.call(nodeList, fn)。fn.bind(obj) 回傳一個 this 永久固定在新函式,適合用於回呼。偽古典繼承有幾個明顯缺點,實務上很少單獨使用:
Animal.prototype 上的方法完全拿不到。因此現代做法是原型鏈繼承,並搭配 Object.create 或 ES6 的 class / extends:
class Animal {
constructor(name) { this.name = name; }
showName() { console.log(this.name); } // 方法掛在原型上,所有實例共用
}
class Cat extends Animal {
constructor(name) {
super(name); // 等同 Animal.call(this, name)
}
}
ES6 的 class 背後仍是原型,但語法清楚、方法共用、也支援 super。把 call/apply 當成理解 this 與繼承原理的敲門磚,實際開發則優先用 class 語法,這是最省力的組合。