为什么可以't我在箭头函数中访问“this”

Why can't I access `this` within an arrow function?

本文关键字:函数 访问 this 为什么      更新时间:2023-09-26

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

因此,无论周围的作用域是什么,都将成为箭头函数的作用域。