co icon indicating copy to clipboard operation
co copied to clipboard

can we capture `this` in out co-ed generator function?

Open huan opened this issue 8 years ago • 3 comments

I use co inside my class method function, and lost this in closures inside co when I call it via a instance...

example code:

const co = require('co')

class Test {
  constructor() {
    this.id = 3
  }

  test_with_bind_this() {
    co(function* () {
      console.log(this.id)
    }.bind(this))
  }

  test() {
    co(function* () {
      console.log(this.id)
    })
  }
}

const t = new Test()
t.test()
// output undefined
t.test_with_bind_this()
// output 3

is there a easy way to bind to this automatically?

huan avatar May 22 '16 11:05 huan

I usually do co.call(ctx, function*() {}) which is not very bothering

luckydrq avatar May 23 '16 00:05 luckydrq

image

??

alsotang avatar Jun 20 '16 07:06 alsotang

@alsotang Thank you! Sorry, my bad. I've removed my misguiding comment.

gunar avatar Jun 20 '16 16:06 gunar