下面这段代码应该按预期工作,并记录"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
并且当您将arrow函数转换为实际的function
声明时,它将起作用。似乎有了箭头功能,我再也无法访问this
。这里发生了什么?
需要明确的是,上面的代码在下面的代码中不起作用,我很好奇为什么。
function Cat () {
this.animalNoise = 'meow'
}
Cat.prototype.sound = function() {
console.log(this.animalNoise)
}
let cat = new Cat()
cat.sound()
箭头函数执行词法绑定,并将周围的范围用作的范围this
。例如,假设(出于某种奇怪的原因)您Cat
在Dog
构造函数内部进行了定义。
function Dog() {
// do dog like things
function Cat() { ... }
Cat.prototype.sound = () => {
// this == instance of Dog!
};
}
因此,无论周围范围是什么,都将成为箭头函数的范围。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句