紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS this:不同呼叫方式下指向什麼與常見錯誤

JS this:不同呼叫方式下指向什麼與常見錯誤 特色圖片

JS this 是 JavaScript 的運算式,在函式裡代表「這次呼叫所屬的物件」。依 MDN 的說法,它像是語言在執行函式本體時自動綁定的一個隱含參數,值取決於函式「如何被呼叫」,而不是函式「定義在哪裡」。

const test = {
  prop: 42,
  func() {
    return this.prop;
  },
};

console.log(test.func());   // 42

這裡 func() 是透過 test.func() 呼叫的,所以 this 就是 test。同一個函式換一種呼叫方式,this 就可能變成別的值。

本文先列出各情境下 this 的值,再依序說明常見的情況與出錯的地方。

this 的值:依情境整理

下表依 MDN 的說明整理,詳細規則在後面各節。

情境this 的值備註
obj.method() 方法呼叫obj,也就是呼叫時點號左邊的物件沿著原型鏈找到的方法也一樣
func() 單獨呼叫非嚴格模式是 globalThis,嚴格模式是 undefined非嚴格模式會做 this 替換
箭頭函式沿用建立時外層的 this自己沒有 this
new Func()新建立的物件建構函式回傳物件時,以該物件為結果
class 的實例方法與欄位實例靜態成員則是類別本身
addEventListener() 的一般函式綁定監聽器的元素箭頭函式不適用
腳本最上層globalThisES 模組最上層是 undefined

補充說明:本文的範例在 Node.js v22.20.0 執行(檔案為 CommonJS,預設是非嚴格模式);DOM 相關範例在 Chrome 158 的無頭模式執行。Node.js 與瀏覽器的差異會在對應段落註明。

方法呼叫:this 是點號左邊的物件

函式以 obj.f() 的形式呼叫時,this 是 obj。MDN 強調,this 是「呼叫時存取函式的那個物件」,不是「擁有函式的物件」,所以同一個函式掛在不同物件上,會得到不同的 this:

function getThis() {
  return this;
}

const obj1 = { name: "obj1" };
const obj2 = { name: "obj2" };

obj1.getThis = getThis;
obj2.getThis = getThis;

console.log(obj1.getThis() === obj1);   // true
console.log(obj2.getThis() === obj2);   // true

方法是從原型鏈上找到的,也是同樣的規則。下面的 obj3 自己沒有 getThis,是從原型 obj1 找到的,但 this 仍然是 obj3:

const obj3 = {
  __proto__: obj1,
  name: "obj3",
};

console.log(obj3.getThis());   // { name: 'obj3' }

把一個物件的方法指派給另一個物件後呼叫,this 也跟著改變:

const obj4 = {
  name: "obj4",
  getThis() {
    return this;
  },
};

const obj5 = { name: "obj5" };

obj5.getThis = obj4.getThis;
console.log(obj5.getThis());   // { name: 'obj5', getThis: [Function: getThis] }

單獨呼叫:嚴格模式與非嚴格模式不同

函式不經過物件、直接以 func() 呼叫時,this 要看是否在嚴格模式(strict mode):

  • 嚴格模式:this 是 undefined。
  • 非嚴格模式:undefined 和 null 會被替換成 globalThis,這個行為稱為 this 替換(this substitution)。
function getThisSloppy() {
  return this;
}

function getThisStrict() {
  "use strict";
  return this;
}

console.log(getThisSloppy() === globalThis);   // true
console.log(typeof getThisStrict());           // undefined

globalThis 是全域物件(global object,樂詞網譯為「總體物件」),在瀏覽器就是 window。

this 的值是原始值(primitive)時,兩種模式的處理也不同:嚴格模式維持原始值,非嚴格模式會把它包成對應的包裝物件。下面的範例為了示範而修改內建的 Number.prototype,實際專案不應該這樣做:

Number.prototype.getThisSloppy = getThisSloppy;
Number.prototype.getThisStrict = getThisStrict;

console.log(typeof (1).getThisSloppy());   // object
console.log(typeof (1).getThisStrict());   // number

補充說明:class 內的程式碼和 ES 模組一律是嚴格模式,不需要寫 "use strict"。

常見錯誤:把方法抽出來後 this 不見了

this 看的是呼叫方式,所以只要把方法從物件上拿出來單獨呼叫,this 就不再是原本的物件。這是最常遇到的 this 問題。

非嚴格模式下,抽出來的方法會把 this 當成 globalThis,而且不會報錯:

const counter = {
  count: 0,
  inc() {
    this.count++;
    return this.count;
  },
};

console.log(counter.inc());   // 1

const inc = counter.inc;
console.log(inc());           // NaN

inc() 單獨呼叫時,this 是 globalThis,this.count++ 讀到 undefined 再加 1,結果是 NaN,並且在全域物件上多出一個 count 屬性。這種錯誤沒有任何錯誤訊息,很難察覺。

換成 class 的方法,因為 class 內是嚴格模式,抽出來呼叫時 this 是 undefined,會直接丟出錯誤:

class Car {
  sayHi() {
    console.log(`Hello from ${this.name}`);
  }

  get name() {
    return "Ferrari";
  }
}

const car = new Car();
car.sayHi();   // Hello from Ferrari

const carSayHi = car.sayHi;

try {
  carSayHi();
} catch (e) {
  console.log(e.name, "|", e.message);
}
// TypeError | Cannot read properties of undefined (reading 'name')

錯誤訊息的文字依引擎而異,上面是 Node.js v22.20.0 的輸出。

最直接的解法是在呼叫的地方保留物件,例如把呼叫包進箭頭函式 () => counter.inc(),或者在 inc 這類要當成回呼函式傳出去的地方,使用 Function.prototype.bind() 先固定 this。call()、apply() 與 bind() 的用法本文不展開。

箭頭函式:沿用外層的 this

箭頭函式(arrow function)沒有自己的 this,它在建立的當下,從外層作用域取得 this,之後不再改變。所以箭頭函式的 this 看的是「定義在哪裡」,和一般函式相反。

這個特性很適合用在方法裡面的回呼函式:

const obj = {
  getThisGetter() {
    const getter = () => this;
    return getter;
  },
};

const fn = obj.getThisGetter();
console.log(fn() === obj);   // true

getter 是在 getThisGetter() 裡建立的,當時的 this 是 obj,所以之後不論怎麼呼叫 fn(),結果都是 obj。

在計時器的回呼函式使用箭頭函式,就能直接取得外層方法的 this:

const timer = {
  name: "timer",
  start() {
    setTimeout(() => {
      console.log(this.name);
    }, 0);
  },
};

timer.start();   // timer

箭頭函式的 this 無法被 call()、apply()、bind() 改變,這些方法傳入的 this 會被忽略(其他引數仍有效):

console.log(fn.call({ x: 1 }) === obj);       // true
console.log(fn.bind({ x: 1 })() === obj);     // true

另一個常見的陷阱:物件字面值的屬性用箭頭函式時,this 不是那個物件。物件字面值不會建立新的 this 範圍,所以箭頭函式的外層是物件所在的位置(這裡是檔案最上層):

const objA = {
  name: "objA",
  arrowProp: () => this,
};

console.log(objA.arrowProp() === objA);   // false

補充說明:在全域程式碼裡,箭頭函式的 this 是 globalThis,嚴格模式下也一樣。Node.js 的 CommonJS 檔案例外:檔案被包在函式裡執行,最上層的 this 是 module.exports,所以上面的箭頭函式在 Node.js 回傳的是 module.exports。

建構函式與 new:this 是新建立的物件

以 new 呼叫函式時,this 是這次新建立的物件。建構函式(constructor,樂詞網譯為「建構子」)通常就是用 this 替新物件加上屬性:

function C() {
  this.a = 37;
}

let o = new C();
console.log(o.a);   // 37

如果建構函式回傳的是物件,new 運算式的結果就是那個物件,而不是 this:

function C2() {
  this.a = 37;
  return { a: 38 };
}

o = new C2();
console.log(o.a);   // 38

new 運算子本身的運作方式,另有專文說明,這裡只需要記住:new 呼叫時 this 是新物件。

class:實例、靜態成員與 super() 之前

class 內有兩種情境。實例方法、建構函式與實例欄位的初始式裡,this 是實例;靜態方法、靜態欄位與靜態初始化區塊裡,this 是類別本身(或繼承它的子類別):

class K {
  instanceField = this;
  static staticField = this;

  static who() {
    return this;
  }
}

const k = new K();
console.log(k.instanceField === k);   // true
console.log(K.staticField === K);     // true
console.log(K.who() === K);           // true

class Sub extends K {}
console.log(Sub.who() === Sub);       // true

衍生類別(用 extends 繼承)的建構函式一開始沒有 this,要呼叫 super() 之後才會建立。在 super() 之前使用 this,或建構函式沒有呼叫 super() 就結束,都會丟出 ReferenceError:

class Base {}

class Bad extends Base {
  constructor() {}
}

try {
  new Bad();
} catch (e) {
  console.log(e.name, "|", e.message);
}
// ReferenceError | Must call super constructor in derived class before accessing 'this' or returning from derived constructor

錯誤訊息的文字依引擎而異,上面是 Node.js v22.20.0 的輸出。class 本身的完整用法,可前往 class 的語法文觀看。

回呼函式:由呼叫它的 API 決定

把函式當作回呼函式(callback)傳給別的 API 時,this 由那個 API 呼叫函式的方式決定,函式自己不能決定。多數 API 呼叫回呼函式時,this 是 undefined:

function logThis() {
  "use strict";
  console.log(this);
}

[1, 2].forEach(logThis);
// undefined
// undefined

有些 API 提供 thisArg 參數,例如陣列的 forEach() 與其他迭代方法,可以指定回呼函式的 this:

[1, 2].forEach(logThis, { name: "obj" });
// { name: 'obj' }
// { name: 'obj' }

也有 API 會替回呼函式固定一個 this。例如 JSON.parse() 的 reviver,以及 JSON.stringify() 的 replacer,被呼叫時的 this 是正在處理的那個屬性所屬的物件。要確認某個 API 的回呼函式 this 是什麼,請查該 API 的文件。

DOM 事件:this 是綁定監聽器的元素

用 addEventListener() 加上的一般函式,被呼叫時 this 是綁定監聽器的元素,也就是 event.currentTarget:

<button id="btn">Click</button>

<script>
  const btn = document.getElementById("btn");

  btn.addEventListener("click", function (e) {
    console.log(this === btn);                // true
    console.log(this === e.currentTarget);    // true
  });

  btn.addEventListener("click", (e) => {
    console.log(this === window);             // true
    console.log(this === btn);                // false
  });
</script>

第二個監聽器是箭頭函式,它沿用外層的 this,所以在腳本最上層就是 window,不是按鈕。要用 this 取得元素時,請用一般函式;要沿用外層的 this 時,才用箭頭函式。

HTML 屬性寫的行內事件處理器(例如 onclick),this 也是該元素;但處理器裡面再包一層函式,內層函式的 this 就不是元素了:

<button id="inline" onclick="console.log(this.tagName.toLowerCase(), (function () { return this === window; })())">
  Inline
</button>
<!-- 點擊後印出:button true -->

MDN 另外提到,用 addEventListener() 以外的方式加上的監聽器,各瀏覽器的行為可能不同。addEventListener() 的語法、選項與 this 的細節,可前往 JS addEventListener() 的語法文觀看。

getter 與 setter:看存取的物件

getter 與 setter 的 this,是存取(或設定)這個屬性的物件,而不是定義它的物件:

function sum() {
  return this.a + this.b + this.c;
}

const o = {
  a: 1,
  b: 2,
  c: 3,
  get average() {
    return (this.a + this.b + this.c) / 3;
  },
};

Object.defineProperty(o, "sum", {
  get: sum,
  enumerable: true,
  configurable: true,
});

console.log(o.average, o.sum);   // 2 6

sum 原本是獨立的函式,被當成 o.sum 的 getter 後,this 就是 o。

全域與模組最上層

腳本最上層的 this 是 globalThis,嚴格與非嚴格模式都一樣。在瀏覽器的一般 <script> 裡,this === window 為 true:

<script>
  console.log(this === window);    // true

  this.b = "MDN";
  console.log(window.b);           // MDN
</script>

幾種看起來像最上層、實際不是的情況:

  • ES 模組:最上層的 this 永遠是 undefined,包含 <script type="module"> 與 Node.js 的 .mjs 檔。
  • Node.js 的 CommonJS 檔案:程式碼被包在函式裡執行,最上層的 this 是 module.exports。
  • 物件字面值:不會建立新的 this 範圍,裡面的值沿用外層的 this。
  • eval():直接呼叫的 eval() 沿用外層的 this,間接呼叫則是 globalThis。
// Node.js CommonJS 檔案
console.log(this === module.exports);   // true

const lit = { a: this };
console.log(lit.a === module.exports);  // true

注意事項

  1. this 看呼叫方式,不看定義位置:同一個函式每次呼叫的 this 都可能不同。一般函式、方法適用這條。
  2. 箭頭函式相反,看定義位置:它沿用外層的 this,不能被 call()、apply()、bind() 改變。
  3. 方法抽出來單獨呼叫會遺失 this:非嚴格模式變成 globalThis(不報錯),嚴格模式與 class 內變成 undefined(會報錯)。
  4. 要用元素的 this 時,事件監聽器別用箭頭函式:箭頭函式的 this 不是元素。
  5. 物件字面值的屬性用箭頭函式時,this 不是該物件:物件字面值不會建立 this 範圍。
  6. 衍生類別要先 super() 才能用 this:否則是 ReferenceError。
  7. 模組最上層的 this 是 undefined:不能拿它當全域物件用,要全域物件請用 globalThis。
  8. 非嚴格模式會把原始值包成物件:嚴格模式不會,兩者的行為不同。

支援版本

this 是語法的一部分,很早就有支援。依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24):

環境最早支援的版本
Chrome1
Edge12
Firefox1
Safari1
Node.js0.10.0

MDN 把 this 標為 Baseline Widely available,並註明自 2015 年 7 月起各主流瀏覽器都支援。Deno 從 1.0 開始支援,Internet Explorer 4 起支援。

參考資料與延伸閱讀

發佈留言