对象内部 this 内部箭头函数的值

新手上路,请多包涵

我以为我理解了 this 和箭头函数之间的关系,但下面的片段让我质疑我的理解。

 let person = {
  name: 'Jim',
  sayName: () => {
    console.log(this.name);
  }
};

person.sayName();

我知道箭头函数捕获 this 封闭上下文的值。我期待 this 会是对象,但它是 Window

有人可以帮我理解为什么会这样吗?

原文由 Tekeste Kidanu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 710
2 个回答

你对箭头函数的理解大部分是正确的:箭头函数有一个词法 this 并且它在箭头函数内的值由周围的范围决定。

您可能假设 thisperson 对象文字中获得不同的值。 事实并非如此

那么让我们看看 this 在您的(全局)范围内指的是什么:

 console.log(this === window); // true

let person = {
  name: 'Jim',
  test: console.log(this === window), // true
  sayName: () => {
    console.log(this === window); // true
  }
};

person.sayName();

如您所见,当创建分配给 sayName 的箭头函数时, this 指的是 window 对象。

原文由 le_m 发布,翻译遵循 CC BY-SA 3.0 许可协议

TLDR;

这样想,“如果我使用非箭头函数,那么 this 会是什么?”然后你可以回忆起箭头函数中的 this 将是更外层的范围 this 与其对应物相比。

例子

 let arrow = {
  test: () => {
    console.log('arrow: this === window...', this === window);
  }
};

let nonarrow = {
  test: function() {
    console.log('non-arrow: this === window...', this === window);
  }
};

arrow.test()
nonarrow.test();

原文由 EyuelDK 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏