本文通過具體代碼演示 JavaScript 中函數調用模式與方法調用模式下 this 綁定的本質區別。
var doubling = function(x) {
return x * 2;
};
var obj = {
val: 100,
prop: function() {
var that = this;
document.write('name: ' + that + '; type: ' + typeof(that) + '<br/>');
return doubling(that.val);
}(),
get_prop: function() {
var that = this;
document.write('name: ' + that + '; type: ' + typeof(that) + '<br/>');
return doubling(that.val);
}
};
name: [object Window]; type: object。立即執行的匿名函數屬於函數調用模式,this 綁定全局對象 window。doubling(that.val) 對 window.val(undefined)運算,返回 NaN。name: [object Object]; type: object。方法調用模式下 this 綁定 obj 本身。doubling(that.val) 正確返回 200。this 綁定全局對象(瀏覽器中為 window)。this 綁定調用該方法的對象。this 綁定。理解此機制對避免 this 指向錯誤導致的 Bug 至關重要,也是 JavaScript 面向對象編程的基石。