this 是 JavaScript 最令人困惑也最核心的機制之一。它的值**在函式被呼叫時決定**,而非定義時。本文系統整理四種標準調用模式、常見陷阱、ES6 箭頭函式解決方案與現代最佳實務。
this = window/globalThisfunction test() {
console.log(this); // window (瀏覽器) / global (Node.js)
}
test();
// 嚴格模式下
function testStrict() {
'use strict';
console.log(this); // undefined
}
testStrict();
設計缺陷:許多人認為這是語言設計失誤,內部函式也會綁定到全域:
var obj = {
method: function() {
console.log(this); // obj
function inner() {
console.log(this); // window!非預期
}
inner();
}
};
this = 呼叫物件var obj = {
name: 'Tom',
greet: function() {
console.log(this.name); // 'Tom'
}
};
obj.greet(); // this 綁定 obj
// 動態綁定特性
var greet = obj.greet;
greet(); // this 變成 window!丟失綁定
this = 新建立的實例function Dog(name) {
this.name = name; // this 指向新實例
this.bark = function() {
console.log(this.name + '汪汪');
};
}
var wangcai = new Dog('旺財');
wangcai.bark(); // "旺財汪汪"
// 忘記 new 的後果
var oops = Dog('忘記new'); // this 指向 window!
console.log(window.name); // "忘記new" - 污染全域
防禦寫法:
function Dog(name) {
if (!(this instanceof Dog)) {
return new Dog(name); // 自動修正
}
this.name = name;
}
call/apply/bind 顯式綁定模式function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
var person = { name: 'Tom' };
greet.call(person, 'Hello', '!'); // 參數逐個傳遞
greet.apply(person, ['Hi', '~']); // 參數用陣列傳遞
var boundGreet = greet.bind(person, 'Hey'); // 回傳新函式,this 永久綁定
boundGreet('?'); // "Hey, Tom?"
this// 現代標準:addEventListener
element.addEventListener('click', function(e) {
console.log(this); // 觸發事件的元素 (currentTarget)
console.log(e.target); // 實際被點擊元素
});
// 箭頭函式:繼承外層 this
element.addEventListener('click', (e) => {
console.log(this); // 外層 this (通常是 window 或類別實例)
console.log(e.currentTarget); // 取得元素請用 e.currentTarget
});
attachEvent// IE8- 專有
element.attachEvent('onclick', function() {
console.log(this); // window!非元素
});
// 這是導致 jQuery 內部需大量修正 this 的主因
thisvar obj = {
value: 42,
getValue: function() { return this.value; }
};
setTimeout(obj.getValue, 100); // undefined - this 變 window
// 解決方案
setTimeout(obj.getValue.bind(obj), 100); // bind
setTimeout(() => obj.getValue(), 100); // 箭頭函式
setTimeout(function() { obj.getValue(); }, 100); // 閉包
$('#btn').click(obj.handler); // jQuery: this 會被綁定為元素
// 解決:$.proxy 或 bind
$('#btn').click($.proxy(obj.handler, obj));
$('#btn').click(obj.handler.bind(obj));
var { method } = obj;
method(); // this = undefined (嚴格模式) 或 window
// 解決
var { method: boundMethod } = obj; // 不行
var boundMethod = obj.method.bind(obj); // 正確
class Component {
constructor() {
this.value = 1;
// ❌ 錯誤:每次 render 建立新函式,無法移除監聽
this.el.addEventListener('click', () => this.handleClick());
// ✅ 正確:建構函式建立一次 bound 函式
this.boundHandleClick = this.handleClick.bind(this);
this.el.addEventListener('click', this.boundHandleClick);
}
handleClick() { console.log(this.value); }
destroy() {
this.el.removeEventListener('click', this.boundHandleClick);
}
}
forEach/map 回調的 this[1,2,3].forEach(function(x) {
console.log(this); // window/undefined
}, thisArg); // 第 2 參數指定 this
// 現代:箭頭函式自動捕獲外層 this
[1,2,3].forEach(x => console.log(this));
bind 多次無效function fn() { console.log(this.a); }
var obj1 = { a: 1 };
var obj2 = { a: 2 };
var bound = fn.bind(obj1).bind(obj2);
bound(); // 1 - 第一次 bind 勝出,後續 bind 無效
this 徹底解決var obj = {
value: 42,
// 箭頭函式沒有自己的 this,繼承外層 (此處為全域/模組)
arrow: () => console.log(this.value),
// 一般函式有自己的 this
method() {
console.log(this.value); // 42
// 內部箭頭函式捕獲 method 的 this
setTimeout(() => console.log(this.value), 100); // 42
}
};
this 判斷決策樹thisnew 呼叫**?→ this = 新實例call/apply/bind**?→ this = 指定物件obj.fn())?→ this = objthis = window/globalThis (非嚴格) / undefined (嚴格)掌握 this 機制,是從「能寫出跑的代碼」進階到「寫出健壯、可維護、可測試代碼」的關鍵門檻。