萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

深度解析 JavaScript this 綁定:四大調用模式、箭頭函數與實戰陷阱

this 是 JavaScript 最靈活也最讓人困惑的機制。它的值**在函數被調用時決定**(運行期綁定),而非定義時。本文系統梳理四種調用模式、箭頭函數的詞法綁定、常見坑點與最佳實踐。

四種調用模式決定 this

1. 方法調用模式 — this 指向調用者

const obj = {
  value: 1,
  inc() { this.value++; }
};
obj.inc(); // this === obj

2. 函數調用模式 — this 指向全域物件(嚴格模式為 undefined)

function foo() { console.log(this); }
foo(); // window / undefined

**設計缺陷**:內部函數無法訪問外層 this,需用 const self = this 或箭頭函數修復。

3. 建構器調用模式 — this 指向新建實例

function Person(name) { this.name = name; }
const p = new Person('Alice'); // this === p

new 會建立空物件、綁定原型、執行函數並回傳該物件。

4. apply / call / bind 顯式綁定 — this 由第一個參數指定

func.call(obj, arg1, arg2);   // 立即執行,this=obj
func.apply(obj, [arg1, arg2]); // 參數為陣列
const bound = func.bind(obj);  // 返回新函數,this 永久綁定 obj

箭頭函數:詞法綁定 this

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) 丟失 thissetTimeout(()=>obj.method(), 100) 或 bind
解構賦值const {method} = obj; method() this 丟失obj.method() 或 const method = obj.method.bind(obj)
類別屬性class fields handleClick = () => {} 自動綁定推薦寫法,避免 constructor 手動 bind

實戰建議

  • 優先使用 **箭頭函數** 作為回調、事件處理器,避免 this 綁定煩惱。
  • 類別方法若需傳遞給外部調用,用 handleClick = () => {}(Class Fields)或 constructor 內 this.handleClick = this.handleClick.bind(this)。
  • 避免在回調中依賴 this 訪問外部狀態,改用閉包捕獲變量或傳參數。
copyright © 萬盛學電腦網 all rights reserved