JavaScript 中 this 關鍵字的指向

Dail LogDail Log
1 min read

1. 在方法 (method) 中

this 出現在物件的方法內部時,它指向的是調用該方法的物件

const obj = {
  name: "Coffee",
  greet() {
    console.log(this.name); // this 指向 obj
  },
};

obj.greet(); // Coffee

2. 在普通函式 (function) 中

如果一個函式不是透過物件調用,而是直接執行,那麼 this非嚴格模式下 (non-strict mode) 指向 window(在瀏覽器環境中),而在嚴格模式 (strict mode) 則是 undefined

function sayHello() {
  console.log(this);
}

sayHello(); // 非嚴格模式:window,嚴格模式:undefined

3. 在構造函式 (constructor function) 中

當函式透過 new 關鍵字呼叫時,this 指向新創建的物件。

function Person(name) {
  this.name = name;
}

const user = new Person("Stanley");
console.log(user.name); // Stanley

4. 在箭頭函式 (arrow function) 中

箭頭函式不會創建自己的 this,而是繼承外部作用域的 this(詞法作用域)。

const obj = {
  name: "Stanley",
  greet: function () {
    const arrowFn = () => {
      console.log(this.name);
    };
    arrowFn(); // this 維持指向 obj
  },
};

obj.greet(); // Stanley

5. 在 setTimeout 或事件監聽器中

  • setTimeout 中的 this(普通函式):指向 window

  • setTimeout 中的 this(箭頭函式):繼承外部作用域

const obj = {
  name: "Coffee",
  greet: function () {
    setTimeout(function () {
      console.log(this.name); // this 指向 window
    }, 1000);

    setTimeout(() => {
      console.log(this.name); // this 指向 obj
    }, 1000);
  },
};

obj.greet();

總結

  1. 方法內的 this 指向調用該方法的物件

  2. 一般函式內的 this(非嚴格模式)指向 window,嚴格模式下是 undefined

  3. new 關鍵字呼叫時,this 指向新物件。

  4. 箭頭函式沒有自己的 this,繼承外部作用域的 this

  5. setTimeout、事件監聽等情境可能會改變 this 指向,要注意是否需要 bind 或箭頭函式來保持 this


若遇到 this 指向的 bug,可使用 console.log(this) 來確認當前指向,或使用 .bind() 修正指向。

0
Subscribe to my newsletter

Read articles from Dail Log directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dail Log
Dail Log