call 方法
語法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定義:呼叫一個物件的方法,並以另一個物件取代當前的 this。
說明:call 可以讓函數的物件上下文從原本的歸屬,切換成 thisObj 指定的新物件。若未提供 thisObj,Global 物件會被當作 thisObj。
apply 方法
語法:apply([thisObj[,argArray]])
定義:應用某一物件的方法,並以另一個物件取代當前的 this。
說明:若 argArray 不是有效的陣列或 arguments 物件,會丟出 TypeError。若 thisObj 與 argArray 都未提供,Global 物件會作為 thisObj,且無法傳入任何參數。
function add(a,b)
{
alert(a+b);
}
function sub(a,b)
{
alert(a-b);
}
add.call(sub,3,1);
這行的意思是「用 add 取代 sub 來執行」,等同於 add(3,1),所以結果是 alert(4)。
這裡有個關鍵前提必須牢記:在 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();
//通過call或apply方法,將原本屬於Animal對象的showName()方法交給對象cat來使用了。
//輸入結果為"Cat"
animal.showName.call(cat,",");
//animal.showName.apply(cat,[]);
cat 本身並沒有 showName 方法。call 的作用就是把 animal 的 showName 掛到 cat 上執行,因此函數內的 this 指向 cat,this.name 自然是 "Cat"。
function Animal(name){
this.name = name;
this.showName = function(){
alert(this.name);
}
}
function Cat(name){
Animal.call(this, name);
}
var cat = new Cat("Black Cat");
cat.showName();
Animal.call(this, name) 的意思是「用 Animal 取代 this」。執行後,Cat 的 this 上就有了 Animal 的所有屬性與方法,於是 cat 可以直接呼叫 showName。這是 JavaScript 裡最基礎的建構繼承手法。
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);
}
連續兩個 call 就完成了多重繼承——把兩個「父類」的成員都掛到同一個 this 上。
當然,JavaScript 的繼承還有其他做法,例如原型鏈,那不在本文範圍內,這裡只是順帶說明 call 的用法。
兩者產生的效果完全一樣,唯一的差異在參數形式:call 的第二個參數之後可以是任意個、任意型別的值;apply 的第二個參數必須是陣列或 arguments 物件。
所以實務上的判斷很簡單:參數個數固定就用 call,參數是現成的陣列或 arguments 就用 apply。此外還有 callee、caller 等相關概念,有興趣可以再往下讀。