this 是 JavaScript 面試的必考題,但它的規則其實很明確:取決於「怎麼被呼叫」,而不是「在哪裡定義」。
在全域範圍下,alert(this) 會得到 [object Window]。直接呼叫的函式中也是:
function sayHello(){ alert(this); }
sayHello(); // [object Window]
在嚴格模式('use strict')下,這種情況的 this 會是 undefined,而不是 window。
var user = "the Window";
var box = {
user: 'the box',
getThis: function(){ return this.user; },
getThis2: function(){ return function (){ return this.user; } }
};
box.getThis() 回傳 the box,因為 this 就是 box。
但 box.getThis2()() 回傳 the Window。原因是外層函式執行完就返回了,最後呼叫的是一個「獨立函式」,此時 this 回到全域。這正是閉包中 this 指向的經典陷阱。
box.getThis2.call(box) 會得到 the box——call 與 apply 的第一個參數就是 this 要指向的物件,兩者差別只在後續參數是逐一傳入(call)還是用陣列傳入(apply)。
function sum(num1, num2){ return num1 + num2; }
function box(num1, num2){ return sum.apply(this, [num1, num2]); }
console.log(box(10, 10)); // 20
這裡 box 借用(冒充)了 sum 的邏輯,同時把自身的 this 傳進去。apply 的 this 繼承,是實作繼承與借用方法時的常用手法。
function Person(){ console.log(this) }
var p = new Person();
透過 new 呼叫時,JavaScript 會先建立一個空物件並讓 this 指向它,執行函式後再把這個物件回傳。
當函式被當作事件處理器時,this 指向觸發事件的元素。而在 ES6 之後,箭頭函式沒有自己的 this,它會沿用定義時所在外層的 this,這解決了絕大多數「this 跑掉」的問題——例如在物件方法中寫 setTimeout(() => this.run(), 100),this 依然正確。理解 this 的四種情境加上箭頭函式的例外,實務上就夠用了。