很多難纏的 JavaScript bug,追到源頭往往都是同一件事:作者以為 this 指向某個東西,實際上不是。原因在於 JavaScript 的 this 並非如 C# 或 Java 那樣由詞法位置決定,而是由「怎麼呼叫」決定。以下用一個小函式把五種呼叫方式逐一跑過。
<script type="text/javascript">
function makeArray(arg1, arg2) {
return [this, arg1, arg2];
}
</script>
makeArray('one', 'two');
// => [ window, 'one', 'two' ]
alert(typeof window.methodThatDoes'tExist); // undefined
alert(typeof window.makeArray); // function
window.makeArray('one', 'two');
// => [ window, 'one', 'two' ]
直接用 myFunction() 呼叫時,this 會是預設的全域物件,在瀏覽器裡就是 window。這也說明為什麼在頁面上宣告的函式會掛到 window 上——而污染全域命名空間,正是 JavaScript 裡最該避免的習慣之一。
規則一:沒有明確所有者物件、直接呼叫的函式,this 為預設的全域物件。
var arrayMaker = {
someProperty: 'some value here',
make: makeArray
};
arrayMaker.make('one', 'two');
// => [ arrayMaker, 'one', 'two' ]
// 中括號寫法效果相同
arrayMaker['make']('one', 'two');
// => [ arrayMaker, 'one', 'two' ]
函式定義完全沒改,this 卻變成物件本身。原因是函式在 JavaScript 裡就是一種資料型別(嚴格說是物件),可以被複製、傳遞。把 makeArray 指派給 make 屬性,等同於在物件裡重新定義了一次:
var arrayMaker = {
someProperty: 'some value here',
make: function (arg1, arg2) {
return [this, arg1, arg2];
}
};
規則二:以 obj.myFunction() 或 obj['myFunction']() 形式呼叫時,this 為 obj。
<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 是被直接呼叫的。第三顆按鈕把處理函式寫在 onclick 屬性裡,本質上和 btn2 相同,結果也一樣。
這正是 jQuery 這類函式庫的價值所在:它會幫你重新導向 this,讓事件回呼裡的 this 穩定指向觸發事件的元素。
// 使用 jQuery,this 必定是被點擊的按鈕
$('#btn1').click(function () {
alert(this.id);
});
當你需要把函式傳到別的上下文執行,又不想複製一份,就得靠函式物件自帶的這兩個方法:
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 因為能直接吃陣列,通常更順手。
規則三:想在不複製函式的前提下改寫 this,用 myFunction.apply(obj) 或 myFunction.call(obj)。
// 宣告建構函式
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,你在建構子裡設定的屬性全都會被掛到全域物件上,而且因為沒有回傳值,呼叫結果是 undefined。這也是為什麼慣例要用大寫字母開頭命名建構函式——它是一個視覺提醒,叫你別忘了 new。
規則四:把函式當初始化函式(MyFunction())呼叫時,執行環境會把 this 指定為新建立的物件。
五種呼叫方式對應四條規則,記住「this 由呼叫形式決定,不由定義位置決定」這一句,多數 this 相關的 bug 都能在幾分鐘內定位。而在現代寫法中,箭頭函式提供了另一條路:它沒有自己的 this,會沿用外層作用域的值,這讓回呼裡的 this 行為變得可預期得多。