JavaScript 函數調用方式決定了函數內部 this 的指向。掌握這五種模式是避免 this 相關 Bug 的關鍵。
function add(a, b) { return this; }
add(1, 2); // 非嚴格模式:window / 全域物件
// 嚴格模式:undefined
this 綁定全域物件(非嚴格)或 undefined(嚴格)。this,需用 const self = this 或箭頭函數。const obj = {
value: 42,
getValue() { return this.value; }
};
obj.getValue(); // 42 —— this 綁定 obj
this 綁定該物件。const f = obj.getValue; f() → 變為函數調用模式,this 丟失。function Person(name) {
this.name = name;
}
const p = new Person('Alice');
// new 過程:
// 1. 建立空物件 {}
// 2. 物件.__proto__ = Person.prototype
// 3. Person.call(物件, 'Alice') → this 指向新物件
// 4. 回傳新物件(除非構造函數顯式 return 物件)
console.log(p.name); // Alice
new 強制建立新物件並綁定 this。new。function greet(greeting, punctuation) {
return greeting + ', ' + this.name + punctuation;
}
const user = { name: 'Bob' };
greet.call(user, 'Hello', '!'); // "Hello, Bob!"
greet.apply(user, ['Hi', '?']); // "Hi, Bob?"
// 箭頭函數無法用 call/apply 改變 this
this 與參數。call 參數列舉,apply 參數陣列。const obj = {
value: 1,
regular() { return this.value; },
arrow: () => this.value
};
obj.regular(); // 1
obj.arrow(); // undefined (全域/模組作用域的 this)
this。arguments、無 prototype、call/apply/bind 無效。this 的場景。new 建構子調用 → 新物件call/apply/bind 顯式綁定 → 指定物件obj.fn() → objfn() → 全域/undefinedthis| 場景 | 問題 | 解決 |
|---|---|---|
| 事件處理器 | this 指向 DOM 元素 | 箭頭函數 / bind / e.currentTarget |
| setTimeout 回調 | this 丟失 | 箭頭函數 / bind |
| 陣列方法回調 | this 為 undefined/全域 | 箭頭函數 / 第二參數 thisArg |
| 解構賦值方法 | const {method} = obj; method() 丟失 this | const {method: bound} = obj; 或 obj.method() |
| Class 方法傳遞 | class 方法提取後 this 丟失 | constructor 中 bind / Public class fields 箭頭函數 |
this。this.method = this.method.bind(this) 或使用 Public Class Fields method = () => {}。addEventListener + 箭頭函數,或 handler.bind(this)。fn.call(context, ...args) 適配。this = undefined,更早暴露 Bug。