Why can't I access `this` within an arrow function? [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-12-19 21:56:46

问题


This code below should work as expected, and log "meow", here an example.

function Cat () {
  this.animalNoise = 'meow' 
}

Cat.prototype.sound = () => {
  console.log(this.animalNoise)
}

let cat = new Cat()
cat.sound()

It doesn't work, this error appears TypeError: Cannot read property 'animalNoise' of undefined and when you convert the arrow function to an actual function declaration it works. It seems like with the arrow function, I no longer have access to this. What's going on here?

To be clear, the above code does not work where the following does, and I'm very curious why.

function Cat () {
  this.animalNoise = 'meow' 
}

Cat.prototype.sound = function() {
  console.log(this.animalNoise)
}

let cat = new Cat()
cat.sound()

回答1:


Arrow functions perform lexical binding and uses the surrounding scope as the scope of this. For example, imagine (for some weird reason) you define Cat inside of a Dog constructor.

function Dog() {
  // do dog like things
  function Cat() { ... }
  Cat.prototype.sound = () => {
    // this == instance of Dog!
  };
}

So whatever the surrounding scope is becomes the scope of an arrow function.



来源:https://stackoverflow.com/questions/34208195/why-cant-i-access-this-within-an-arrow-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!