在ES6类中嵌套引用“this”
以下面的例子;
class MyClass { run() { this.hello = 1; co(function*() { this.hello // this is now 'undefined' }) } } new MyClass().run()
在ES5中,我通常会在函数的开头将this
分配给另一个variables,例如var cls = this
,但是我希望ES6 / ES7现在可以解决这个问题。
有一个更好的方法吗?
你可以使用bind
:
class MyClass { run() { this.hello = 1; co(function*() { this.hello // 1 }.bind(this)); } } new MyClass().run()