const obj = {
method() {
console.log(this === obj); // true
function inner() {
console.log(this === obj); // false!嚴格模式下 undefined,非嚴格下 window
}
inner();
}
};
obj.method();
**原因:** 普通函數的 this 由**呼叫方式**決定,而非定義位置。inner() 為普通呼叫,this 指向全域物件(或嚴格模式下 undefined)。
const obj = {
method() {
console.log(this === obj); // true
const inner = () => {
console.log(this === obj); // true!箭頭函數沒有自己的 this,繼承外層詞法作用域的 this
};
inner();
}
};
const obj = {
method() {
const self = this; // 或 that、_this
function inner() {
console.log(self === obj); // true
}
inner();
}
};
function inner() {
console.log(this === obj);
}
inner.call(obj); // 立即呼叫並綁定
inner.bind(obj)(); // 返回綁定後的新函數再呼叫
class MyClass {
method() {
console.log(this instanceof MyClass); // true
const inner = () => {
console.log(this instanceof MyClass); // true
};
inner();
}
}
// 或物件字面量
const obj = {
method() {
const inner = () => { /* ... */ };
inner();
}
};
class UI {
constructor() {
this.count = 0;
// ❌ 錯誤:click 時 this 指向 button 元素
// document.querySelector("button").addEventListener("click", this.handleClick);
// ✅ 正確:箭頭函數綁定實例 this
document.querySelector("button").addEventListener("click", () => this.handleClick());
// ✅ 正確:bind
// document.querySelector("button").addEventListener("click", this.handleClick.bind(this));
}
handleClick() {
console.log(this.count++); // 正確訪問實例屬性
}
}
| 場景 | 推薦方案 |
|---|---|
| 物件/類別內部巢狀函數 | 箭頭函數 |
| 需動態綁定不同 this | bind / call / apply |
| 舊環境無 Babel/Transpile | const self = this |
| 事件監聽器 | 箭頭函數或 bind(this) |
| 回調函數(如 setTimeout) | 箭頭函數 |