看下面的例子;
class MyClass {
run() {
this.hello = 1;
co(function*() {
this.hello // this is now 'undefined'
})
}
}
new MyClass().run()
在 ES5 中我通常会分配 this
到函数开头的另一个变量,例如 var cls = this
,但我希望 ES6/ES7 现在能够解决这个问题。
有更好的方法吗?
最佳答案
您可以使用bind
:
class MyClass {
run() {
this.hello = 1;
co(function*() {
this.hello // 1
}.bind(this));
}
}
new MyClass().run()
关于node.js - ES6 类中对 `this` 的嵌套引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37458925/