this 是物件導向語言裡的關鍵字,但 JavaScript 的 this 跟 Java、C# 那種「就是目前物件」的直覺不同,它的值在函式被呼叫的當下才決定,這也是許多人卡住的原因。以下用六種常見情境逐一說明。
var name = 'this is window';
function getName() {
console.log(this); // Window
console.log(this.name); // this is window
}
getName();
在非嚴格模式下,直接呼叫的函式裡 this 指向全域物件;若開啟 strict mode,則會是 undefined。
var name = 'this is window';
var testObj = {
name: 'this is testObj',
getName: function () {
console.log(this); // testObj
console.log(this.name); // this is testObj
}
};
testObj.getName();
規則很簡單:this 指向「呼叫這個方法的東西」,也就是 testObj,而不是外層的 window。
function getObj() {
console.log(this); // getObj {}
}
new getObj();
用 new 執行時,JavaScript 會先造一個空物件並把它綁到 this 上,最後回傳該物件。
var name = 'this is window';
var testObj = {
name: 'this is testObj',
getName: function () {
var self = this; // 先把外層的 this 存起來
var handle = function () {
console.log(this.name); // this is window
console.log(self.name); // this is testObj
};
handle();
}
};
testObj.getName();
巢狀函式被單獨呼叫時,this 又回到全域物件,這被普遍視為 JavaScript 的設計缺陷——幾乎沒有人期待這種行為。傳統解法是把外層 this 存進 that 或 self 再用;ES5 之後可以用 bind,ES6 的箭頭函式則會沿用外層的 this,是更乾淨的寫法。
var testObj1 = {
name: 'this is testObj1',
getName: function () { console.log(this.name); }
};
var testObj2 = { name: 'this is testObj2' };
testObj1.getName.call(testObj2); // this is testObj2
testObj1.getName.apply(testObj2); // this is testObj2
兩者差別只在後續參數的形式:call 使用參數列表,apply 使用陣列。
fn.call(thisArg, arg1, arg2); fn.apply(thisArg, [arg1, arg2]);
這是最容易出錯的一環,三種寫法結果不同:
<!-- 寫在標籤上 -->
<button id="btn" onclick="btClick();">點擊</button>
<script>
function btClick() { console.log(this); } // Window
</script>
在 HTML 屬性裡呼叫,函式是被「呼叫」而非被當成方法,因此 this 是全域物件。
// 在 JS 中指定函式
document.getElementById("btn").onclick = btClick;
// this → 按鈕元素
// 在 JS 中指定匿名函式
document.getElementById("btn").onclick = function () {
console.log(this); // 按鈕元素
};
// addEventListener
document.getElementById("btn").addEventListener('click', btClick);
// this → 按鈕元素(attachEvent 則是 window)
結論:除了 HTML 行內寫法與老 IE 的 attachEvent,其餘在 JavaScript 中綁定的事件處理器,this 都指向觸發事件的那個元素。
this 不屬於函式本身,而屬於「呼叫方式」。搞不清楚 this 時,先問一句:這個函式是被誰、以什麼形式呼叫的?答案通常就出來了。