为什么可以't我在箭头函数中访问“this”
Why can't I access `this` within an arrow function?
下面的代码应该按预期工作,并记录"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()
Arrow函数执行词法绑定,并使用周围的作用域作为this
的作用域。例如,假设(出于某种奇怪的原因)在Dog
构造函数中定义Cat
。
function Dog() {
// do dog like things
function Cat() { ... }
Cat.prototype.sound = () => {
// this == instance of Dog!
};
}
因此,无论周围的作用域是什么,都将成为箭头函数的作用域。
相关文章:
- javascript函数访问ios本机功能
- 从嵌套函数访问函数属性
- 将typescript函数访问到angular中
- 全局变量只能由第一个函数访问
- Javascript从匿名函数访问外部对象属性
- UI网格:如何从自定义函数访问MODEL_COL_FIELD
- 在jQuery中,我如何从$.ajax回调函数访问$(this)
- 如何在JavaScript中停止从特定函数访问某些函数和变量
- 从jQuery.ech()函数访问外部作用域
- Angular2/Typescript:从链接可观察函数访问实例变量
- 局部变量仍可通过函数访问
- 从Kendo中的columns.filterable.cell.template函数访问列字段名
- 可以't从JS函数访问combodate
- 如何在javascript中将变量从一个函数访问到另一个函数
- jQuery从PHP函数访问Ajax响应
- 如何从json函数访问javascript中的基类变量
- 在OPP JS中,您可以从构造函数访问原型函数内部声明的方法
- Javascript 使用函数访问其他类
- 从 JavaScript 中的私有函数访问公共函数
- 为什么我无法从茉莉花中的 javascript 函数访问全局变量