【问题标题】:ES6 in NodeJS: Arrow functions in object literal, what is the returned 'this' value? [duplicate]NodeJS中的ES6:对象文字中的箭头函数,返回的“this”值是什么? [复制]
【发布时间】:2016-02-22 06:41:05
【问题描述】:

我只是在玩箭头函数,并尝试将它们用作对象文字中的属性,如下所示:

var obj = {
  a: () => {
    return this;
  },
  b: function () {
    return this;
  },
};

但是,当我对此进行测试时,我无法完全解释从 obj.a() 返回的 this 是什么。

console.log(obj.a()); //=> {}
console.log(obj.b()); //=> { a: [Function], b: [Function] }

obj的原型吗?

【问题讨论】:

  • 不,这是定义obj 的上下文。在模块/严格模式中,它将是 undefined

标签: javascript node.js ecmascript-6


【解决方案1】:

这很可能是指 nodejs default object(相当于窗口)。它可能被定义为其他东西,具体取决于您的对象所在的范围。

如果您的项目中有use strict,这将是未定义的。

【讨论】:

    【解决方案2】:

    胖箭头函数将返回父级的作用域。意味着在这种情况下没有用,因为它会给你返回错误的范围。

    当您想要在同一范围内获得回调时,粗箭头很有用。 (还记得var self = this吗?)

    var obj = {
        txt: 'TEXT',
      a: function (cb) {
        return cb();
      },
      b: function () {
          var self = this;
          this.a(function() { // Normal funciton, you need the self
              //console.log(val);
              console.log(this.txt)
              console.log(self.txt);
          })
      },
      c: function () {
          this.a(() => {
              console.log(this.txt)
          })
      },
    };
    
    console.log('--- B')
    obj.b();
    console.log('--- C')
    obj.c();
    

    【讨论】:

      【解决方案3】:

      a中的返回对象为全局对象,如果设置use strict则为undefined。

      var obj = {
        a: () => {
      //this = global scope
          return this;
        },
        b: function () {
          return this;
        },
      };
      

      【讨论】:

      • 正如其他人提到的,这也取决于你的对象是从哪里调用的,在这种情况下它是全局范围
      猜你喜欢
      • 2022-11-27
      • 2022-01-14
      • 2018-02-07
      • 1970-01-01
      相关资源
      最近更新 更多