【问题标题】:Nested reference to `this` in ES6 classes [duplicate]ES6类中对`this`的嵌套引用[重复]
【发布时间】:2016-05-26 10:59:28
【问题描述】:

举个例子;

class MyClass {
  run() {
    this.hello = 1;
    co(function*() {
      this.hello // this is now 'undefined'
    })
  }
}
new MyClass().run()

在 ES5 中,我通常会将 this 分配给函数开头的另一个变量,例如 var cls = this,但我希望 ES6/ES7 现在能够解决这个问题。

有没有更好的方法来做到这一点?

【问题讨论】:

  • this 问题由箭头函数解决,只是箭头函数语法不支持生成器。所以要么使用bind,要么使用const(而不是var)。

标签: node.js ecmascript-6


【解决方案1】:

你可以使用bind:

class MyClass {
  run() {
    this.hello = 1;
    co(function*() {
      this.hello // 1
    }.bind(this));
  }
}
new MyClass().run()

【讨论】:

  • 如果我使用.bind(),那么我将如何引用co.this
  • @sleepycal cothisglobal,你不需要它。通常bind 不适用于生成器函数,但与co 一起使用是安全的。
  • @estus 对于co以外的库,有没有更好的方法,还是重新分配cls = this这个标准?
  • @sleepycal 理想情况下,好的代码不应该在生成器和普通函数之间产生差异,两者都可以返回可迭代对象。无论如何,有一个代码可能依赖于检测它们。我正在使用一个助手来绑定它们,function genBind(fn, ctx) { let bound = fn.bind(ctx); Object.setPrototypeOf(bound, Object.getPrototypeOf(fn)); return bound; }。对于普通函数,只需查看bind 和箭头即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 2021-08-07
  • 2016-12-12
  • 1970-01-01
  • 2018-08-01
相关资源
最近更新 更多