【发布时间】:2016-03-16 11:03:22
【问题描述】:
下面的代码应该可以按预期工作,并记录"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。这里发生了什么?
需要明确的是,上面的代码不起作用下面的代码不起作用,我很好奇为什么。
function Cat () {
this.animalNoise = 'meow'
}
Cat.prototype.sound = function() {
console.log(this.animalNoise)
}
let cat = new Cat()
cat.sound()
【问题讨论】:
-
与函数表达式相比,箭头函数表达式(也称为胖箭头函数)的语法更短,并且词法绑定 this 值 -- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
已经有多个关于此的问题。请使用搜索。
-
不过,总的来说,我很好奇人们如何/在哪里了解箭头函数没有也了解
this在箭头函数中的行为。这种差异是箭头函数不可或缺的一部分,我似乎不可能不知道它。
标签: javascript this ecmascript-6 arrow-functions