this 在函數被呼叫時決定,而非定義時同一個函數,依呼叫方式不同,this 指向會改變。四種呼叫模式:
this 指向該物件const point = {
x: 0, y: 0,
moveTo(dx, dy) {
this.x += dx;
this.y += dy;
}
};
point.moveTo(1, 1); // this === point
this 指向全域物件(瀏覽器為 window,嚴格模式為 undefined)function foo() { console.log(this); }
foo(); // 非嚴格模式:window;嚴格模式:undefined
陷阱: 內部函數(巢狀函數)同樣遵循此規則,導致 this 丟失外層物件。
const obj = {
val: 1,
outer() {
function inner() { console.log(this.val); } // this 指向 window/undefined
inner();
}
};
obj.outer(); // undefined 或報錯
解決方案: 箭頭函數(無自身 this,捕獲外層)或 const self = this / bind。
new) → this 指向新建立的實例function Point(x, y) {
this.x = x;
this.y = y;
}
const p = new Point(1, 2); // this === p
慣例:建構函數首字母大寫,提醒呼叫者需用 new。
call / apply / bind 顯式綁定 → this 指向傳入的第一個參數function greet(greeting) { console.log(greeting + ', ' + this.name); }
const user = { name: 'Alice' };
greet.call(user, 'Hello'); // Hello, Alice
greet.apply(user, ['Hi']); // Hi, Alice
const bound = greet.bind(user);
bound('Hey'); // Hey, Alice
function Foo() {
if (this instanceof Foo) {
console.log('建構函數呼叫');
} else if (this === window) {
console.log('全域函數呼叫');
} else {
console.log('物件方法呼叫,this 指向:', this.constructor.name);
}
}
Foo(); // 全域函數呼叫
Foo.call({}); // 物件方法呼叫
new Foo(); // 建構函數呼叫
this(回呼、事件處理器)。class fields 箭頭函數或建構函數中 this.method = this.method.bind(this)。this,開啟 "use strict" 讓錯誤更早暴露。掌握四大綁定規則(隱式、隱式丟失、顯式、new),搭配箭頭函數與 bind,即能駕馭 this,寫出可預測、可維護的 JavaScript 程式碼。