JavaScript中this的動態綁定機制是許多開發者的痛點。本文通過一個經典案例,層層剖析this在不同調用模式下的指向規則,幫助徹底理解「誰調用,指向誰」的核心原則。
var name = "The Window";
var object = {
name: "My Object",
getNameFunc: function() {
return function() {
return this.name;
};
}
};
alert(object.getNameFunc()()); // 輸出什麼?
輸出:"The Window"
原因:this在函數執行時動態確定,取決於調用方式而非定義位置。
| 調用模式 | 代碼示例 | this指向 | 備註 |
|---|---|---|---|
| 方法調用 | obj.method() | obj | 點號前的對象 |
| 函數調用 | func() | window (嚴格模式下undefined) | 最常見陷阱來源 |
| 構造器調用 | new Constructor() | 新創建的實例 | this綁定到新對象 |
| apply/call/bind | func.call(ctx, ...) | 指定的ctx | 顯式綁定,優先級最高 |
// 1. object.getNameFunc() → 方法調用,this = object // 返回內部匿名函數引用(未執行) // 2. object.getNameFunc()() → 緊接著對返回函數進行「函數調用」 // 此時無「對象.」前綴,屬於普通函數調用 // this → window (非嚴格模式) // 3. 內部函數返回 this.name → window.name → "The Window"
// 情況A:賦值給變量再調用
var func = object.getNameFunc;
func(); // 函數調用 → this = window
// 情況B:箭頭函數(詞法綁定this)
var object2 = {
name: "Arrow Object",
getNameFunc: () => {
return () => this.name; // 此處this = object2
}
};
alert(object2.getNameFunc()()); // "Arrow Object"
// 情況C:用bind固定this
var boundFunc = object.getNameFunc().bind(object);
alert(boundFunc()); // "My Object"
this.bind(this)或() => fn.call(this)this.method = this.method.bind(this)"use strict"下普通函數調用this=undefined,更易暴露問題