this 是 JavaScript 中最容易搞混的關鍵字之一。它並不像其他語言那樣「固定指向當前物件」,而是取決於函式被怎麼呼叫。以下用四個情境把規則講清楚。
<script type="text/javascript">
function t() {
alert(this); // 這裡 this 表示 window 物件
}
t();
</script>
嚴格模式下,這種情況的 this 會是 undefined 而非 window——這正是嚴格模式用來避免誤寫全域變數的設計。
<html>
<head>
<script type="text/javascript">
function t() {
alert(this);
this.style.background = 'green';
}
window.onload = function () {
document.getElementById('eng').onclick = t;
};
</script>
</head>
<body>
<p id="eng">abcd</p>
</body>
</html>
點擊段落後,t 內的 this 指向該 p 元素,因此背景變成綠色。規則是:函式作為某物件的屬性被呼叫時,this 就是那個物件,與函式在哪裡定義無關。
<script type="text/javascript">
function dog() {
this.legs = 4;
this.bark = function () {
alert("汪汪...");
};
}
var wangcai = new dog();
wangcai.bark();
</script>
用 new 呼叫時,引擎會先建立一個空物件、把 this 綁定到它上面,最後(若函式沒有明確回傳物件)把它回傳。
注意:若直接呼叫 dog() 而不加 new,就退化成情境一,this 指向 window,而 wangcai 會是 undefined。這是新手最常踩的坑。
補充觀念:
{ name: 'abc', age: 40 } 字面值建立,也可以用建構函式建立。new 函式名() 方式呼叫的普通函式。函式本身沒有「是不是建構函式」的標記。
function greet(greeting) {
alert(greeting + ',我是 ' + this.name);
}
var person = { name: '大熊' };
greet.call(person, '你好'); // 你好,我是 大熊
greet.apply(person, ['早安']); // 早安,我是 大熊
var bound = greet.bind(person);
bound('晚安'); // 晚安,我是 大熊
三者差異:call 逐一傳參數,apply 傳陣列,bind 回傳一個 this 已固定的新函式。
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var hi = document.getElementById('hi');
if (hi.addEventListener) { // chrome 和 firefox
hi.addEventListener('click', function () {
alert(this.id); // W3C 模型中 this 指向 DOM 物件,結果為 hi
}, false);
} else { // ie8 及更早
hi.attachEvent('onclick', function () {
alert(this.id); // 這裡 this 指向 window,結果為 undefined
});
}
};
</script>
</head>
<body>
<p id="hi">hello world</p>
</body>
</html>
同樣是點擊同一個元素,W3C 標準模型下 this 指向該元素,而 IE 的 attachEvent 下 this 指向 window。這是不相容行為的典型例子。
ES6 的箭頭函式沒有自己的 this,它會沿用外層作用域的 this:
var obj = {
name: '大熊',
items: [1, 2, 3],
show: function () {
this.items.forEach(() => {
console.log(this.name); // 這裡的 this 是 obj
});
}
};
obj.show();
若改用一般函式作為 forEach 的回呼,this 會變成 window 或 undefined,就必須先用 var self = this 繞路。箭頭函式正是為了解決這個痛點而生。但要注意:箭頭函式因此不能用 call/apply/bind 改變 this,也不適合當建構函式或物件方法。
出發點只有一個問題:這個函式是怎麼被呼叫的? 直接呼叫看嚴格模式、作為屬性呼叫看所屬物件、用 new 呼叫看新物件、用 call/apply/bind 看指定值、箭頭函式看外層作用域。