網路上關於 call 的定義往往寫得很拗口。用一句話概括:a.call(b, arg1, arg2) 就是把 a 的方法拿來用在 b 身上。理解了這句話,後面的應用都很自然。
function add(a, b)
{
alert(a + b);
}
function reduce(a, b)
{
alert(a - b);
}
add.call(reduce, 1, 3); // 把 add 的方法套用到 reduce,結果為 4
這裡 add 借用了 reduce 作為「this」,於是 add 內部的 this 指向 reduce 函式本身。
function b()
{
alert(this)
}
b(); // window
b.call(); // window
b.call("a", 2, 3); // a
在非嚴格模式下,不指定 this 時預設指向全域物件 window;一旦透過 call 傳入第一個參數,this 就被替換成那個值。這正是 call 最核心的能力。
再來看一個稍複雜的例子:
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(); // animal
animal.showName.call(cat); // cat
Cat 原本沒有 showName 方法,透過 call,animal 的 showName 被套用到 cat 上,而方法內的 this 也隨之指向 cat,因此印出 cat。
function Animal(name)
{
this.name = name;
this.showName = function()
{
alert(this.name)
}
}
function Cat(name)
{
Animal.call(this, name); // 把 Animal 套用到 Cat,Cat 因此擁有 Animal 的所有屬性與方法
}
var cat = new Cat("Black Cat");
cat.showName(); // 瀏覽器彈出 Black Cat
關鍵在 Animal.call(this, name):在 Cat 的建構过程中借用 Animal 的建構式,this 指向正在建立的 Cat 物件,於是 Animal 裡用 this 掛上的屬性與方法全都長到了 Cat 身上。這是所謂的「建構式繼承」。
要注意它的侷限:這種方式只繼承了 Animal 建構式中設定的成員,若方法掛在 Animal.prototype 上,就拿不到。要完整繼承,通常得搭配原型鏈,例如 Cat.prototype = Object.create(Animal.prototype)。
a.call(b, arg1, arg2, ...); a.apply(b, [arg1, arg2]); // apply 只有兩個參數,其餘參數打包成陣列傳入
除此之外,兩者的行為完全一致。實務上的選擇很簡單:參數個數已知且固定用 call;參數來源是一個陣列(例如 function 裡的 arguments)就用 apply。兩者都能達成同樣目的,差別只在寫法是否順手。