this 是 JavaScript 最靈活也最讓人困惑的機制。它的值**在函數被調用時決定**(運行期綁定),而非定義時。本文系統梳理四種調用模式、箭頭函數的詞法綁定、常見坑點與最佳實踐。
const obj = {
value: 1,
inc() { this.value++; }
};
obj.inc(); // this === obj
function foo() { console.log(this); }
foo(); // window / undefined
**設計缺陷**:內部函數無法訪問外層 this,需用 const self = this 或箭頭函數修復。
function Person(name) { this.name = name; }
const p = new Person('Alice'); // this === p
new 會建立空物件、綁定原型、執行函數並回傳該物件。
func.call(obj, arg1, arg2); // 立即執行,this=obj
func.apply(obj, [arg1, arg2]); // 參數為陣列
const bound = func.bind(obj); // 返回新函數,this 永久綁定 obj
const obj = {
value: 42,
normal() { setTimeout(function() { console.log(this.value); }, 100); }, // undefined
arrow() { setTimeout(() => console.log(this.value), 100); } // 42
};
箭頭函數**沒有自己的 this**,捕獲定義時外層作用域的 this,**不能**用 call/apply/bind 改變。
| 場景 | 問題 | 解決 |
|---|---|---|
| 事件監聽器 | el.addEventListener('click', fn) 中 this 指向 el | 用箭頭函數或 fn.bind(this) |
| 回調函數 | setTimeout(obj.method, 100) 丟失 this | setTimeout(()=>obj.method(), 100) 或 bind |
| 解構賦值 | const {method} = obj; method() this 丟失 | obj.method() 或 const method = obj.method.bind(obj) |
| 類別屬性 | class fields handleClick = () => {} 自動綁定 | 推薦寫法,避免 constructor 手動 bind |
handleClick = () => {}(Class Fields)或 constructor 內 this.handleClick = this.handleClick.bind(this)。this 訪問外部狀態,改用閉包捕獲變量或傳參數。