以下代码应如预期般工作,并记录"meow"
,这里有一个示例。
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
。这是怎么回事?
明确一点,上面的代码不起作用,而下面的代码可以正常工作,我非常好奇为什么。
function Cat () {
this.animalNoise = 'meow'
}
Cat.prototype.sound = function() {
console.log(this.animalNoise)
}
let cat = new Cat()
cat.sound()
this
的行为时,如何/从何处学习箭头函数。这个差异是箭头函数的一个重要部分,因此不知道它似乎对我来说是不可能的。 - Felix Kling