this 指向的物件。由「如何調用函數」決定。if/for/while 區塊內的 var 變數會「提升」至函數頂部。let/const 提供真正區塊作用域。| 調用方式 | this 指向 | 範例 |
|---|---|---|
| 物件方法調用 | 該物件 | obj.foo() → this = obj |
建構函數 new | 新建立的實例 | new Foo() → this = 實例 |
| 普通函數調用 | 全域物件(瀏覽器為 window) | foo() → this = window |
| 嚴格模式普通調用 | undefined | "use strict"; foo() → this = undefined |
call/apply/bind | 指定的第一個參數 | fn.call(obj) → this = obj |
function first(){ second(); }
function second(){ third(); }
function third(){ fourth(); }
function fourth(){ /* do something */ }
first();
呼叫堆疊(作用域鏈頂→底):fourth → third → second → first → global。
尋找變數:從當前執行上下文變數物件開始,沿作用域鏈向上直到全域。同名變數,越內層優先級越高。
當內部函數在外部函數返回後仍被引用,形成閉包,保有對外部函數變數、參數、函數宣告的存取權。
function foo(){
var local = 'private';
return function bar(){ return local; };
}
var getLocal = foo();
getLocal(); // "private" —— 仍能存取已返回的 foo 作用域變數
var Module = (function(){
var privateProp = 'foo';
function privateMethod(){ /* ... */ }
return {
publicProp: '',
publicMethod: function(){ /* ... */ },
privilegedMethod: function(){ privateMethod(); }
};
})();
(function(window){
var a = 'foo';
window.Module = { public: function(){ /* ... */ } };
})(this);
保護全域命名空間,常用於程式庫封裝。
function user(first, last, age){ /* ... */ }
user.call(window, 'John', 'Doe', 30); // 參數列表
user.apply(window, ['John', 'Doe', 30]); // 參數陣列
if (!Function.prototype.bind) {
Function.prototype.bind = function(){
var fn = this, context = arguments[0],
args = Array.prototype.slice.call(arguments, 1);
return function(){
return fn.apply(context, args);
};
};
}
// 事件處理綁定 this
function MyClass(){
this.el = document.createElement('div');
this.el.addEventListener('click', this.onClick.bind(this), false);
}
MyClass.prototype.onClick = function(e){ /* this 正確指向實例 */ };
// arguments、NodeList 非真陣列,但可借用陣列方法
var argsArr = Array.prototype.slice.call(arguments, 1);
var divsArr = Array.prototype.slice.call(document.getElementsByTagName('div'));
bind 固定回調上下文,避免事件處理器 this 指向錯誤。