萬盛學電腦網

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

JavaScript `this` 綁定全圖解:從迷失到精通的 4 大規則與實戰陷阱

核心原則:`this` 在「調用時」決定,而非「定義時」

同一個函數,因調用方式不同,`this` 指向完全不同。掌握 **4 大綁定規則**(優先級由高到低):

1. 新綁定 —— `new` 調用

function Person(name) {
  this.name = name; // this → 新建的空物件
}
const p = new Person('Alice');
console.log(p.name); // 'Alice'
  • `new` 會創建新物件,將 `this` 指向它,並隱式返回該物件。
  • 箭頭函數**不能**用 `new` 調用(無 `[[Construct]]` 內部方法)。

2. 顯式綁定 —— `call` / `apply` / `bind`

function greet(greeting, punctuation) {
  console.log(`${greeting}, ${this.name}${punctuation}`);
}
const user = { name: 'Bob' };

greet.call(user, 'Hello', '!');        // Hello, Bob!
greet.apply(user, ['Hi', '~']);        // Hi, Bob~
const bound = greet.bind(user, 'Hey'); // 返回新函數,this 永久綁定 user
bound('?');                            // Hey, Bob?
  • `call` 參數逐個傳遞,`apply` 接受陣列/類陣列。
  • `bind` 返回**新函數**,不立即執行,適合回調傳遞。
  • 多次 `bind` 僅第一次生效,`bind` 後再 `call`/`apply` 無法改變 `this`。

3. 隱式綁定 —— 物件方法調用

const obj = {
  name: 'Obj',
  say() { console.log(this.name); }
};
obj.say(); // 'Obj' — this → obj

// ⚠️ 陷阱:分離調用丟失綁定
const fn = obj.say;
fn(); // 'Window' / undefined (strict) — this 丟失!

// 修正:bind 固定 this
const boundFn = obj.say.bind(obj);
boundFn(); // 'Obj'

4. 預設綁定 —— 獨立函數調用

function foo() { console.log(this); }
foo(); // 非嚴格模式 → window / globalThis
       // 嚴格模式 ('use strict') → undefined

特殊規則:箭頭函數無 `this`,繼承外層詞法作用域

const obj = {
  name: 'Obj',
  regular() { console.log(this.name); },      // 'Obj'
  arrow:  () => console.log(this.name)        // 繼承外層(模組頂層 → window/undefined)
};
obj.regular(); // 'Obj'
obj.arrow();   // 'Window' 或 undefined

// 實戰:類別方法用箭頭函數自動綁定
class Logger {
  prefix = '[LOG]';
  log = (msg) => console.log(this.prefix, msg); // 實例屬性箭頭函數 = 自動 bind
}
const l = new Logger();
setTimeout(l.log, 100, 'test'); // 仍正確輸出 '[LOG] test'

優先級判斷流程圖(文字版)

調用函數 fn()
│
├─ new fn()          → this = 新物件          (最高)
│
├─ fn.call/apply/bind(obj) → this = obj      (顯式綁定)
│
├─ obj.fn()          → this = obj             (隱式綁定)
│
└─ fn()              → this = global/undefined (預設綁定) (最低)

實戰高頻陷阱與解法

場景問題解法
事件監聽器`el.addEventListener('click', obj.handler)` → `this` 指向 `el``obj.handler.bind(obj)` 或箭頭函數 `() => obj.handler()`
回調函數`setTimeout(obj.method, 100)` → `this` 丟失`setTimeout(() => obj.method(), 100)` 或 `obj.method.bind(obj)`
數組方法`[1,2].map(obj.mul)` → `this` 丟失`[1,2].map(x => obj.mul(x))` 或 `.map(obj.mul, obj)` (第 2 參數)
類別繼承`super.method()` 內的 `this` 正確,但提取方法丟失建構子中 `this.method = this.method.bind(this)` 或 Class fields 箭頭函數
DOM 內聯事件`改用 `addEventListener` 或 `onclick="obj.click.call(obj)"`

嚴格模式的影響

'use strict';
function foo() { return this; }
foo(); // undefined(非嚴格模式下為 window)
// 嚴格模式下預設綁定不再指向全域,避免竄改全域汙染

結語

理解 `this` 的 4 大綁定規則與優先級,搭配箭頭函數「無 this、繼承外層」特性,即可解決 99% 的 `this` 指向問題。現代開發建議:類別方法優先用箭頭函數(Class Fields),回調傳遞用 `bind` 或箭頭函數包裹,徹底拒絕 `var self = this` 時代遺留寫法。

copyright © 萬盛學電腦網 all rights reserved