此值不引用当前范围,而是引用 ES6 箭头样式函数中的父范围

this value doesn't reference current scope instead refrences parent scope in ES6 arrow style function

我对 ES6 有点陌生,但对 node js 不是,但这看起来有点奇怪,因为当我开始使用箭头样式函数而不是 function() 样式时,我假设两者完全相同但语法是不同的。但是今天才知道这个案子。

当我这样定义一个函数时。

exports.intent = {
  greetings: {
    matcher: ["hi", "hello"],
    reply: function(){
       console.log(this); // it prints {greetings: {..}} expected
       return this.matcher[0]; // returns "hi" which is expected.
    }
  }
}

但是当我用箭头样式定义相同的函数时,它会抛出错误,因为这里现在引用整个对象而不是当前对象。

exports.intent = {
  greetings: {
    matcher: ["hi", "hello"],
    reply: () => {
       console.log(this); // it prints whole object {intent: {....}}
       return this.matcher[0]; // fail here.
    }
  }
}

我了解到这两种声明之间的引用有一些变化。

有什么方法可以让我仅将其引用到当前对象吗?

没有。您将无法在箭头函数体内覆盖 this 。即使您尝试绑定它,它也不起作用。 This one 是我最近看到的一篇有趣的文章。