ECMAScript 規範中的 引用類型 是一種內部規格類型,不直接暴露給代碼,但通過「標識符解析」與「屬性訪問」產生,核心決定了 this 綁定、賦值操作、delete 操作等語義。本文從規範視角拆解引用類型結構、GetValue 算法、三種調用模式下的 this 綁定規則,並澄清常見誤區。
引用類型值由兩部分組成(偽代碼):
var reference = {
base: , // 基座對象:全局對象、激活對象、或普通對象
propertyName: , // 屬性名稱
strict: // 是否嚴格模式(ES5+)
};
base = globalObjectbase = VariableObject / ActivationObjectobj.prop、obj['prop']。
base = obj(對象本身)function GetValue(V) {
if (Type(V) !== Reference) return V; // 已是值類型直接返回
var base = V.base;
if (base === null) throw new ReferenceError(); // 未聲明變量
return base.[[Get]](V.propertyName); // 內部 [[Get]] 包含原型鏈查找
}
何時觸發 GetValue?
var x = y; → GetValue(yRef)a + b → GetValue(aRef), GetValue(bRef)func() 中 func 先 GetValue 得到函數對象function PutValue(W, V) {
if (Type(W) !== Reference) throw ReferenceError(); // 左值必須是引用
var base = W.base;
if (base === null) throw ReferenceError();
base.[[Put]](W.propertyName, V); // 內部 [[Put]] 創建/更新屬性
}
若調用表達式
MemberExpression Arguments中的MemberExpression求值結果為 引用類型,則this = GetBase(ref);
否則this = undefined(嚴格模式)或globalObject(非嚴格模式)。
| 代碼 | MemberExpression 結果 | 是否引用類型 | base | this 指向 |
|---|---|---|---|---|
obj.foo() | Reference(base=obj, name='foo') | 是 | obj | obj |
(obj.foo)() | Reference(base=obj, name='foo') | 是(分組運算符不觸發 GetValue) | obj | obj |
(obj.foo = obj.foo)() | Function Object (賦值表達式返回值) | 否 | — | global / undefined |
(false || obj.foo)() | Function Object (邏輯或返回值) | 否 | — | global / undefined |
(obj.foo, obj.foo)() | Function Object (逗號運算符返回值) | 否 | — | global / undefined |
foo() (全局函數) | Reference(base=global, name='foo') | 是 | global | global |
var f = obj.foo; f() | Function Object (變量引用函數對象) | 否 | — | global / undefined |
function outer() {
function inner() { console.log(this); }
inner(); // MemberExpression = inner (Identifier) -> Reference(base=AO, name='inner')
// 但規範規定:Activation Object 作為 base 時視為 null -> this = global/undefined
}
outer();
修復:inner.call(this)、var self = this、箭頭函數。
var obj = {
method: function () {
setTimeout(() => { console.log(this); }, 100); // this 綁定外層 method 的 this (obj)
}
};
obj.method();
標識符/屬性訪問
↓
創建 Reference {base, propertyName}
↓
調用表達式 MemberExpression()
↓
若 Reference → this = base
若非 Reference → this = global/undefined
↓
函數體內 this 確定
理解引用類型機制,是徹底掌握 JavaScript this 綁定、避免「this 丟失」Bug 的理論基石。