为什么不能在箭头功能中访问`this`?
下面的代码应可以正常运行,并记录"meow"
,此处为示例.
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()
它不起作用,此错误出现在TypeError: Cannot read property 'animalNoise' of undefined
上,当您将箭头函数转换为实际的function
声明时,它将起作用.似乎有了箭头功能,我不再可以访问this
.这里发生了什么?
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()
箭头函数执行词法绑定 ,并将周围的范围用作this
的范围.例如,假设(出于某种奇怪的原因)您在Dog
构造函数内定义了Cat
.
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.