为什么不能在箭头功能中访问`this`? [英] Why can't I access `this` within an arrow function?

查看:102
本文介绍了为什么不能在箭头功能中访问`this`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码应可以正常运行,并记录"meow"此处为示例.

This code below should work as expected, and log "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.这里发生了什么?

It doesn't work, this error appears TypeError: Cannot read property 'animalNoise' of undefined and when you convert the arrow function to an actual function declaration it works. It seems like with the arrow function, I no longer have access to this. What's going on here?

要清楚,上面的代码在下面的地方不起作用,我很好奇为什么.

To be clear, the above code does not work where the following does, and I'm very curious why.

function Cat () {
  this.animalNoise = 'meow' 
}

Cat.prototype.sound = function() {
  console.log(this.animalNoise)
}

let cat = new Cat()
cat.sound()

推荐答案

箭头函数执行词法绑定 ,并将周围的范围用作this的范围.例如,假设(出于某种奇怪的原因)您在Dog构造函数内定义了Cat.

Arrow functions perform lexical binding and uses the surrounding scope as the scope of this. For example, imagine (for some weird reason) you define Cat inside of a Dog constructor.

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

因此,环绕范围将成为箭头函数的范围.

So whatever the surrounding scope is becomes the scope of an arrow function.

这篇关于为什么不能在箭头功能中访问`this`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆