注意:原文代碼為 JavaScript 而非 PHP。此處保留原標題但修正說明,釐清 JS 中 this 綁定規則。
var doubling = function(x) { return x * 2; };
var obj = {
val: 100,
prop: (function() {
var that = this;
console.log('name: ' + that + '; type: ' + typeof that); // [object Window], object
return doubling(that.val); // this 是 window,val 不存在 → NaN
})(),
get_prop: function() {
var that = this;
console.log('name: ' + that + '; type: ' + typeof that); // [object Object], object
return doubling(that.val); // this 是 obj,val=100 → 200
}
};
| 屬性/方法 | 初始化/呼叫時機 | this 指向 | 結果 |
|---|---|---|---|
prop (IIFE) | 物件字面量定義階段立即執行 | 全域物件 window (非嚴格模式) | NaN |
get_prop() | 後續手動呼叫 obj.get_prop() | 物件 obj | 200 |
func() → this 綁定全域物件 (瀏覽器為 window),嚴格模式為 undefined。obj.method() → this 綁定 obj。new Func() → this 綁定新建實例。this。// 坑:回調函數丟失 this
obj.callback = function() { console.log(this.val); };
setTimeout(obj.callback, 100); // this 變 window
// 修正 1: 箭頭函數 (詞法綁定)
setTimeout(() => obj.callback(), 100);
// 修正 2: bind
setTimeout(obj.callback.bind(obj), 100);
// 修正 3: 變數緩存 (舊寫法)
var that = this;
setTimeout(function() { console.log(that.val); }, 100);
PHP 中 $this 在類方法內永遠指向當前實例,不存在「丟失 this」問題。PHP 5.4+ 支援 Closure::bind / bindTo 手動綁定閉包 $this,但極少直接用於業務代碼。