JavaScript 類中的箭頭函數

類中的箭頭函數 this 等於實例

class Person {
  constructor () {
    this.name = '章三'
  }
  handleClick1 = () => {
    console.log(this.name)
    return this
  }
  handleClick2 () {
    console.log(this.name)
    return this
  }
}
let person = new Person()
console.log(person.handleClick1() === person) // true
console.log(person.handleClick2() === person) // true

我們發現上面代碼中普通函數和箭頭函數沒什麼區別,函數中的 this 都指向實例,但是我們再看看下面的代碼。

class Person {
  constructor () {
    this.name = '章三'
  }
  handleClick1 = () => {
    console.log(this.name)
    return this
  }
  handleClick2 () {
    console.log(this.name)
    return this
  }
}
let person = new Person()
let { handleClick1, handleClick2 } = person
console.log(handleClick1() === person) // true
console.log(handleClick2() === person) // false

我好像理解了,又好像不理解。。。請聽我細細道來!

類的方法內部如果含有 this,它默認指向類的實例。但是,必須非常小心,一旦單獨使用該方法,很可能報錯。

上面代碼中,handleClick2 方法中的 this,默認指向 Person 類的實例。但是,如果將這個方法提取出來單獨使用,this 會指向該方法運行時所在的環境(由於 class 內部是嚴格模式,所以 this 實際指向的是 undefined),從而導致找不到 name 屬性而報錯。

一個比較簡單的解決方法是,在構造方法中綁定 this,這樣就不會找不到 name 屬性了。另一種解決方法是使用箭頭函數,如 handleClick1 的寫法。

在 handleClick1 函數中,箭頭函數內部的 this 總是指向定義時所在的對象。上面代碼中,箭頭函數位於類內部,類本身就指向構造函數。這時,箭頭函數所在的運行環境,肯定是實例對象,所以 this 會總是指向實例對象。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/Dpwy88-IZx0qwtKT9g0hQA