2

Take the following example;

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

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.

Is there a better way to do this?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
SleepyCal
  • 5,739
  • 5
  • 33
  • 47
  • 1
    The `this` problem is solved by arrow functions, except that the arrow function syntax doesn't support generator. So either use `bind` or use `const` (instead of var). – Sheepy May 27 '16 at 02:32

1 Answers1

2

You can use bind:

class MyClass {
  run() {
    this.hello = 1;
    co(function*() {
      this.hello // 1
    }.bind(this));
  }
}
new MyClass().run()
Simone
  • 20,302
  • 14
  • 79
  • 103
  • If I use `.bind()`, then how would I reference `co.this`? – SleepyCal May 26 '16 at 11:05
  • 1
    @sleepycal `co`'s `this` is `global`, you don't need it. Usually `bind` is inappropriate with generator functions, but it is safe to use it with `co`. – Estus Flask May 26 '16 at 11:58
  • @estus For libs other than `co`, is there a better way, or is re-assigning `cls = this` the standard? – SleepyCal May 26 '16 at 11:59
  • 1
    @sleepycal Ideally, a good code shouldn't make a difference between generator and plain function, both can return iterables. Any way, there is a code that may rely on detecting them. I'm using a helper to bind them, `function genBind(fn, ctx) { let bound = fn.bind(ctx); Object.setPrototypeOf(bound, Object.getPrototypeOf(fn)); return bound; }`. For plain functions, look no further than `bind` and arrows. – Estus Flask May 26 '16 at 12:08