traditional() vs arrow()

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 本身。
  • 瀏覽器環境,全域物件是 windowwindow.scope 可能是 "lexical scope",所以可能回傳 "lexical scope"
  • Node.js 環境this 預設不指向 global,所以 this.scope === undefined,回傳 undefined