本文整理自《JavaScript: The Good Parts》的相關章節,重點在於釐清「同一個函數,用不同方式呼叫時 this 究竟指向誰」。
先記住一個前提:JavaScript 呼叫函數時,會額外附贈兩個隱形參數——this 與 arguments。其中 arguments 是類陣列物件,並不是真正的陣列,但可以用 .length 取得長度。
書中歸納出四種呼叫方式:方法呼叫模式、函數呼叫模式、構造器呼叫模式、apply 呼叫模式。
當函數被存成物件的屬性並透過該物件呼叫時,this 指向這個物件本身。
/* 方法呼叫模式 */
var myobject = {
value: 0,
inc: function(){
alert(this.value)
}
}
myobject.inc() // this 指向 myobject
直接呼叫一個函數(而非作為物件方法)時,this 會被綁定到全域物件,在瀏覽器環境中就是 window。
/* 函數呼叫模式 */
var add = function(a, b){
alert(this) // this 被綁定到 window
return a + b;
}
var sum = add(3, 4);
alert(sum)
用 new 呼叫函數時,this 會指向新建立的物件實例。《The Good Parts》一書建議盡量避免這種方式,因為有更好的替代方案(例如 Object.create 這類原型式建立法)。這裡僅列出基本形式:
/* 構造器呼叫模式(不建議) */
var quo = function(string){
this.status = string;
}
quo.prototype.get_status = function(){
return this.status;
}
var qq = new quo("aaa");
alert(qq.get_status());
apply() 的第一個參數決定 this 的指向,第二個參數則是參數陣列。這讓我們可以完全掌控呼叫上下文:
/* apply */ // 沿用上面的 add 函數與 myobject // 這種呼叫方式的優點在於可以指定 this 指向的物件 // apply 的第一個參數就是 this 要指向的物件 var arr = [10, 20]; var sum = add.apply(myobject, arr); alert(sum);
下面這個 bind 函數示範了 apply 在跨瀏覽器事件綁定中的價值:
var bind = function(object, type, fn){
if(object.attachEvent){ // IE 瀏覽器
object.attachEvent("on" + type, (function(){
return function(event){
window.event.cancelBubble = true; // 停止事件冒泡
object.attachEvent = [fn.apply(object)]; // 關鍵在這裡
// 在 IE 中用 attachEvent 綁定事件後,
// 回呼函數裡的 this 並不指向 object 本身,
// 因此 this.id 無法正常工作。
// 改用 fn.apply(object) 把 this 的指向改成 object,
// this.id 就等同於 object.id,可以正確運作。
}
})(object), false);
} else if(object.addEventListener){ // 其他瀏覽器
object.addEventListener(type, function(event){
event.stopPropagation(); // 停止事件冒泡
fn.apply(this)
});
}
}
bind(document.getElementById("aaa"), "click", function(){ alert(this.id) });
把四種模式記成一張表就清楚了:作為方法呼叫時 this 是宿主物件;單純呼叫時 this 是全域物件(嚴格模式下為 undefined);用 new 呼叫時 this 是新實例;用 call/apply 呼叫時 this 由你指定。實務上絕大多數「this 指向不如預期」的困擾,都能用 bind、apply 或箭頭函數來化解。