在ES6类中嵌套引用“ this” [英] Nested reference to `this` in ES6 classes

查看:63
本文介绍了在ES6类中嵌套引用“ this”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用以下示例;

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

在ES5中,我通常会分配 this 到函数开始处的另​​一个变量,例如 var cls = this ,但是我希望ES6 / ES7能够解决此问题。

In ES5 I would normally assign this to another variable at the start of the function, such as var cls = this, but I would have hoped that ES6/ES7 would of solved this problem by now.

有更好的方法吗?

推荐答案

您可以使用 bind

You can use bind:

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

这篇关于在ES6类中嵌套引用“ this”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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