同一個函數,因調用方式不同,`this` 指向完全不同。掌握 **4 大綁定規則**(優先級由高到低):
function Person(name) {
this.name = name; // this → 新建的空物件
}
const p = new Person('Alice');
console.log(p.name); // 'Alice'
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?
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'
function foo() { console.log(this); }
foo(); // 非嚴格模式 → window / globalThis
// 嚴格模式 ('use strict') → undefined
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` 時代遺留寫法。