下面的代码应该按预期工作,并记录"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()