【问题标题】:Why can't I access `this` within an arrow function? [duplicate]为什么我不能在箭头函数中访问“this”? [复制]
【发布时间】: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


【解决方案1】:

Arrow functions perform lexical binding 并使用周围的范围作为this 的范围。例如,假设(出于某种奇怪的原因)您在 Dog 构造函数中定义了 Cat

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

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

【讨论】:

  • 每个函数都是词法范围的。只是this(和arguments)在箭头函数中是特殊的。
  • @FelixKling 好点。编辑后的答案更准确。
猜你喜欢
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 2020-03-08
  • 2016-11-30
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
相关资源
最近更新 更多