
this.scope = "lexical scope"; // 在全域作用域(Node.js 是 global, 瀏覽器是 window)
const scopeOf = {
scope: "defining scope",
traditional: function() {
return this.scope;
},
arrow: () => {
return this.scope;
}
};
console.log(scopeOf.traditional()); // "defining scope"
console.log(scopeOf.arrow()); // undefined(或瀏覽器環境可能為 "lexical scope")
分析 traditional()
方
traditional: function() {
return this.scope;
}
traditional
是用 普通函式function
宣告的。this
會綁定到「呼叫它的物件」,即scopeOf
。- 所以
this.scope === scopeOf.scope
,因此它回傳"defining scope"
。
理解 this
綁定
等價於:
javascript複製編輯console.log(scopeOf.traditional()); // 相當於 scopeOf.traditional.call(scopeOf);
因此:
javascript複製編輯this === scopeOf; // ✅ this 綁定到 scopeOf
this.scope === "defining scope"; // ✅ 回傳 "defining scope"
分析 arrow()
方法
javascript複製編輯arrow: () => {
return this.scope;
}
- 箭頭函式不會創建自己的
this
,它會繼承「外層作用域」的this
(也就是定義函式時的this
,而不是呼叫時的this
)。 - 這裡
scopeOf
物件的外層作用域是 全域作用域,而不是scopeOf
本身。 - 在 瀏覽器環境,全域物件是
window
,window.scope
可能是"lexical scope"
,所以可能回傳"lexical scope"
。 - 在 Node.js 環境,
this
預設不指向global
,所以this.scope === undefined
,回傳undefined
。