先把結論記牢:this 永遠指向函式「執行時」所處的物件,而不是函式「被建立時」所處的物件。這一點記不清,後面全都會亂。以下分三種情境拆解。
無論 this 出現在哪裡,第一步永遠是:找出函式執行的位置。
var name = "全局";
function getName() {
var name = "局部";
return this.name;
}
alert(getName());
this 出現在全域環境的 getName 中,而 getName 的執行位置是 alert(getName())。顯然它所在的物件是全域物件 window,因此 this 指向 window,this.name 其實是 window.name,彈出的是「全局」。注意函式內那個 var name = "局部" 完全沒被用到,這正是初學者最容易誤判的地方。
換成物件方法就不同了:
var name = "全局";
var twobin = {
name: "局部",
getName: function () {
return this.name;
}
};
alert(twobin.getName());
this 所在的 getName 不在全域環境,而在 twobin 之中。執行位置是 alert(twobin.getName()),函式所屬物件是 twobin,因此 this 指向 twobin,結果是「局部」。
閉包就是在一個函式內部建立另一個函式,且內部函式存取了外部的變數。this 遇上閉包,情況就更微妙了。
var name = "全局";
var twobin = {
name: "局部",
getName: function () {
return function () {
return this.name;
};
}
};
alert(twobin.getName()());
此時 this 身處 getName 內部的匿名函式裡。判斷依據不能再用 getName 的執行位置,而要看那個匿名函式的執行位置。匿名函式掛在 window 上執行,因此 this 指向 window,回傳的是 window.name,也就是「全局」。
想讓閉包裡的 this 留在 twobin 上,標準解法是先把它存起來:
var name = "全局";
var twobin = {
name: "局部",
getName: function () {
var that = this;
return function () {
return that.name;
};
}
};
alert(twobin.getName()());
在 getName 中寫下 var that = this,此時 getName 的執行位置是 twobin.getName(),this 指向 twobin,that 自然也指向 twobin。閉包中的匿名函式回傳 that.name,於是正確彈出「局部」。
在 JavaScript 裡,真正管得住 this 的,大概就是 call 與 apply 了。它們像 this 的監護人,指定它住哪它就得住哪。
var name = "全局";
var twobin = {
name: "局部"
};
function getName() {
alert(this.name);
}
getName(twobin);
getName.call(twobin);
第一行 getName(twobin) 雖然傳了參數,但那只是個普通引數,getName 的所屬物件仍是 window,因此 this 指向 window,彈出「全局」。
第二行 getName.call(twobin) 才是真的改寫上下文:call 指定 this 必須在 twobin 上,於是 this.name 變成 twobin.name,彈出「局部」。
this 的指向規則可以濃縮成三句話:
永遠指向函式執行時所處的物件,而非建立時所處的物件;若身處匿名函式或不在任何物件中,則指向 window 物件;若透過 call 或 apply 呼叫,則以它們指定的物件為準。
(補充:在 ES5 嚴格模式下,獨立呼叫的函式其 this 會是 undefined 而非 window;箭頭函式則沒有自己的 this,會沿用了外層詞法作用域的值。)