9

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

1 回答 1

11

箭头函数执行词法绑定并使用周围的范围作为this. 例如,想象一下(出于某种奇怪的原因)您CatDog构造函数中定义。

function Dog() {
  // do dog like things
  function Cat() { ... }
  Cat.prototype.sound = () => {
    // this == instance of Dog!
  };
}

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

于 2015-12-10T17:33:24.973 回答