this 是 JavaScript 裡最容易被低估的關鍵字。它威力強大,但也常讓人栽跟頭。理解它的訣竅其實只有一句:看這個函式是被哪個物件當成方法呼叫的,那個物件就是 this。
var obj = {};
obj.x = 100;
obj.y = function(){ alert(this.x); };
obj.y(); // 彈出 100
obj.y() 是作為 obj 的方法呼叫,函式體內的 this 指向 obj,所以讀到 100。
var checkThis = function(){ alert(this.x); };
var x = 'this is a property of window';
var obj = {};
obj.x = 100;
obj.y = function(){ alert(this.x); };
obj.y(); // 100
checkThis(); // 'this is a property of window'
為什麼第二個會彈出字串?因為有一條規則:全域變數都是 window 物件的屬性。執行 checkThis() 等同於 window.checkThis(),於是 this 指向 window,而 window 上正好有個 x 屬性。
function changeStyle(type, value){
this.style[type] = value;
}
var one = document.getElementById('one');
changeStyle.call(one, 'fontSize', '100px');
changeStyle('fontSize', '300px'); // 報錯:window 沒有 style 屬性
call 的第一個參數指定「這個函式被哪個物件呼叫」,這裡指定了 one,因此函式體內 this 指向 one;後面兩個參數依序對應 type 與 value。不帶物件直接呼叫時 this 是 window,自然會出錯。
changeStyle.apply(one, ['fontSize', '100px']);
apply 與 call 效果相同,只差在參數形式:apply 只收兩個參數,第二個必須是陣列,陣列元素依序對應函式的形參。
var obj = {
x: 100,
y: function(){
setTimeout(function(){ alert(this.x); }, 2000); // undefined
}
};
obj.y();
這裡的 this 指向 window,不是我們期待的 obj,所以彈出 undefined。解法有兩個:
var obj = {
x: 100,
y: function(){
var that = this; // 先把 this 存起來
setTimeout(function(){ alert(that.x); }, 2000);
}
};
obj.y(); // 100
或者用箭頭函式,它沒有自己的 this,會沿用外層的:
y: function(){
setTimeout(() => alert(this.x), 2000);
}
var one = document.getElementById('one');
one.onclick = function(){
alert(this.innerHTML); // this 指向 one 元素
};
function test() {
this.x = 1;
}
var o = new test();
alert(o.x); // 1
用 new 呼叫時,引擎會先造一個空物件並讓 this 指向它,函式執行完再把它回傳。這也是為什麼建構函式裡的 this.x = 1 會變成新物件的屬性。
var x = 0;
function test() { alert(this.x); }
var o = {};
o.x = 1;
o.m = test;
o.m.apply(); // 0,this 是全域物件
o.m.apply(o); // 1
非嚴格模式下,this 的值只看「怎麼被呼叫」,與它在哪裡定義無關。純函式呼叫指向全域物件,方法呼叫指向該物件,new 呼叫指向新物件,call/apply/bind 則由你指定。嚴格模式下純函式呼叫的 this 是 undefined,不再偷偷指向 window;ES6 的箭頭函式則完全放棄自己的 this,改為繼承外層——這兩點是現代 JavaScript 中最重要的補充。