在 JavaScript 中,call、apply 和 bind 是 Function 物件自帶的三個方法,主要作用是改變函數中的 this 指向。
它們的共同點與差別如下:
bind 會回傳對應函數,便於稍後呼叫;apply、call 則是立即呼叫。call() 語法:
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定義:呼叫一個物件的方法,以另一個物件替換當前物件。
call 可將函數的物件上下文從初始上下文改為由 thisObj 指定的新物件。thisObj 的取值有以下 4 種情況:
(1)不傳,或傳 null、undefined,函數中的 this 指向 window 物件
(2)傳遞另一個函數的函數名,this 指向這個函數的引用
(3)傳遞字串、數值或布林等基礎類型,this 指向其對應的包裝物件(String、Number、Boolean)
(4)傳遞一個物件,this 指向這個物件
function a(){ console.log(this); }
function b(){}
var c={name:"call"};
a.call(); //window
a.call(null); //window
a.call(undefined); //window
a.call(1); //Number
a.call(''); //String
a.call(true); //Boolean
a.call(b); //function b(){}
a.call(c); //Object
再看一個例子:
function class1(){
this.name=function(){ console.log("我是class1內的方法"); }
}
function class2(){
class1.call(this); //執行後,當前 this 指向 class1(也可說 class2 繼承了 class1)
}
var f=new class2();
f.name(); //呼叫的是 class1 內的方法
常用例子:
(1)
function eat(x,y){ console.log(x+y); }
function drink(x,y){ console.log(x-y); }
eat.call(drink,3,2); //輸出:5
這裡的意思是用 eat 來替換 drink,eat.call(drink,3,2) 等同於 eat(3,2),結果為 5。注意:js 中的函數其實是物件,函數名是對 Function 物件的引用。
(2)
function Animal(){
this.name="animal";
this.showName=function(){ console.log(this.name); }
}
function Dog(){ this.name="dog"; }
var animal=new Animal();
var dog=new Dog();
animal.showName.call(dog); //輸出:dog
Dog 裡並沒有 showName 方法,但 this.name 的值卻是 dog,關鍵就在最後一句 animal.showName.call(dog)——它把 animal 的方法放到 dog 上執行,所以 this.name 是 dog。
(3)繼承
function Animal(name){
this.name=name;
this.showName=function(){ console.log(this.name); }
}
function Dog(name){
Animal.call(this,name);
}
var dog=new Dog("Crazy dog");
dog.showName(); //輸出:Crazy dog
Animal.call(this) 的意思是用 Animal 物件代替 this,這樣 Dog 就能直接呼叫 Animal 的所有屬性和方法。
語法:apply([thisObj[,argArray]])
定義:應用某一物件的方法,用另一個物件替換當前物件。
說明:如果 argArray 不是有效的數組或 arguments 物件,將導致 TypeError;若未提供任何參數,Global 物件將作為 thisObj。
call 和 apply 的區別:兩者作用完全一樣,只是接受參數的方式不同。
function class1(args1,args2){
this.name=function(){ console.log(args1,args2); }
}
function class2(){
var args1="1";
var args2="2";
class1.call(this,args1,args2); /*或*/
class1.apply(this,[args1,args2]);
}
var c=new class2();
c.name(); //輸出:1 2
call 需要把參數按順序傳遞,而 apply 則把參數放在數組裡。
既然兩者功能一樣,該用哪個呢?當參數數量明確時用 call;當參數數量不確定時用 apply,把參數 push 進數組傳遞。參數數量不確定時,函數內部也可透過 arguments 遍歷所有參數。
bind 是 ECMAScript5 擴展的方法(IE6、7、8 不支援),它與 apply、call 相似,也能改變函數體內 this 的指向。
MDN 的解釋是:bind() 會建立一個新函數(綁定函數),呼叫時以建立時傳入的第一個參數作為 this,傳入的第二個及以後的參數,加上綁定函數執行時自身的參數,按順序作為原函數的參數來呼叫原函數。
注意:bind 的回傳值是函數。
var bar=function(){ console.log(this.x); }
var foo={ x:3 }
bar(); //undefined
bar.bind(foo)(); /*或*/
var func=bar.bind(foo);
func(); //3