this 在 JavaScript 中是個很容易被誤解的主題,主要會跟呼叫方法以及函式類型有關,導致很多非預期的結果出現。讓我們來重新好好認識 this 吧!

傳統函式

傳統函式中的 this 只跟「調用方式」有關,物件下呼叫的 this 基本上都是指向該物件

  • JS() 是直接呼叫,沒有物件當作接頭人
  • 所以 this全域物件(在瀏覽器是 window
  • this.A 變成 window.A,所以是 'Global'
function JS() {
  console.log(this.A);
}
var A = 'Global';
JS(); // => Global

箭頭函式

箭頭函式會自動加上 return(若省略大括號),箭頭函式沒有自己的 thisthis 會繼承外層函式作用域this 請往外層看

  • this 繼承外層
var name = 'Global';
// 傳統函式
const person = {
  name: 'Ming',
  callName: function() {
    console.log('1', this.name);   // Ming

    setTimeout(function() {
      console.log('2', this.name); // Global (simple call)
      console.log('3', this);      // window
    }, 10);
  }
};
person.callName();

// 箭頭函式
const person = {
  name: 'Ming',
  callName: function() {
    console.log('1', this.name);   // Ming

    setTimeout(() => {
      console.log('2', this.name); // Ming
      console.log('3', this);      // person 物件
    }, 10);
  }
};
person.callName();