反覆看到的一些 JavaScript bug,根源都是同一件事:沒有真正理解函式是怎麼被呼叫的。this 的值並非由定義位置決定,而是取決於呼叫的形式。本文用同一個範例函式,示範五種呼叫方式各自帶來的差異。
<script type="text/javascript">
function makeArray(arg1, arg2){
return [ this, arg1, arg2 ];
}
</script>
它什麼都不做,只回傳當下的 this 與兩個參數,正好用來觀察 this 到底是誰。
makeArray('one', 'two');
// => [ window, 'one', 'two' ]
window.makeArray('one', 'two');
// => [ window, 'one', 'two' ] 等價寫法
在瀏覽器中,直接呼叫 myFunction() 時 this 會是 window(嚴格模式下則是 undefined)。同時,用這種語法定義的函式預設就掛在全域物件上,而全域命名空間污染是應該避免的——這在 JavaScript 中尤其如此,多個函式庫共存時衝突幾乎無可避免。
var arrayMaker = {
someProperty: 'some value here',
make: makeArray
};
arrayMaker.make('one', 'two');
// => [ arrayMaker, 'one', 'two' ]
arrayMaker['make']('one', 'two');
// => [ arrayMaker, 'one', 'two' ] 等價寫法
函式定義完全沒變,this 卻換了。原因是函式在 JavaScript 中就是一個普通的值(嚴格說是物件),指派給 make 屬性時,等於把整個函式複製過去,效果等同於:
var arrayMaker = {
someProperty: 'some value here',
make: function (arg1, arg2) {
return [ this, arg1, arg2 ];
}
};
呼叫時的「點」在哪裡,this 就是那個點前面的東西。
<input type="button" value="Button 1" id="btn1" />
<input type="button" value="Button 2" id="btn2" />
<input type="button" value="Button 3" id="btn3" onclick="buttonClicked();"/>
<script type="text/javascript">
function buttonClicked(){
var text = (this === window) ? 'window' : this.id;
alert(text);
}
var button1 = document.getElementById('btn1');
var button2 = document.getElementById('btn2');
button1.onclick = buttonClicked;
button2.onclick = function(){ buttonClicked(); };
</script>
點 btn1 會顯示 btn1,因為這是方法呼叫,this 是被掛上的那個按鈕元素。點 btn2 顯示 window,因為 buttonClicked() 是直接呼叫。btn3 把處理函式寫在 HTML 屬性裡,等同 btn2 的情況,因此結果一樣是 window。
這也是 jQuery 這類函式庫的價值之一:它在觸發事件時會重新指定 this,確保指向事件的來源元素。
$('#btn1').click(function() {
alert(this.id); // jQuery 保證 this 是該按鈕
});
函式作為物件存在,因此自帶一些方法,其中 apply() 與 call() 就是用來指定 this 的。
var gasGuzzler = { year: 2008, model: 'Dodge Bailout' };
makeArray.apply(gasGuzzler, [ 'one', 'two' ]);
// => [ gasGuzzler, 'one', 'two' ]
makeArray.call(gasGuzzler, 'one', 'two');
// => [ gasGuzzler, 'one', 'two' ]
兩者唯一差別是參數傳遞形式:apply() 收一個陣列,call() 則把參數逐一列出。實務上 apply() 在多參數動態組裝時較方便。
function ArrayMaker(arg1, arg2) {
this.someProperty = 'whatever';
this.theArray = [ this, arg1, arg2 ];
}
ArrayMaker.prototype = {
someMethod: function () {
alert('someMethod called');
},
getArray: function () {
return this.theArray;
}
};
var am = new ArrayMaker('one', 'two');
var other = new ArrayMaker('first', 'second');
am.getArray(); // => [ am, 'one', 'two' ]
前面那個 new 是關鍵。少了它,函式就跟直接呼叫一樣,this 指向 window,所有 this.xxx 都會被掛到全域物件上;而且因為建構子沒有回傳值,呼叫端拿到的會是 undefined,後續取值時才爆錯,排查起來很痛苦。這也是業界約定建構子名稱用大寫字母開頭的原因——一個視覺上的提醒。
ES6 新增了以 new.target 判斷呼叫形式的手段,而 Reflect 的 construct 也提供了第五種迂迴路徑。實務上先記住前四條,就足以解釋絕大多數的 this 行為。
ES6 的箭頭函式沒有自己的 this,它會沿用外層定義時的 this,這消滅了「把 this 存成 self 或 _this 再傳進回呼」這個古老而醜陋的 pattern:
button1.addEventListener('click', () => {
console.log(this); // 沿用外層的 this,而非按鈕
});
但要留意:正因如此,箭頭函式不能拿來當方法或建構子。需要 this 指向呼叫者時,還是要用一般函式。理解這五種規則的實際意義,就在於你永遠能預先說出 this 會是什麼——這是遠離這類 bug 的第一步。