1

我试图使用显式的 .bind(this) 并且没有用。我也知道箭头功能在这里不起作用。

'use strict';

const co     = require('co');

class ServiceDemo {

    constructor(repository, config, loggingService) {
        this.config = config;
        this.repository = repository;
        this.loggingService = loggingService;
    }

    checkForNotifications(pricePoint) {

        const self = this;

        return co(function*() {
            self.loggingService.debug('test');
            //const surprisesToNotify = yield this.getSomething(pricePoint);
        });
    }

    getSomething(){
        return co(function*() {
            return {};
        });
    }

}

module.exports = SurpriseSchedulerService;

4

2 回答 2

3

co 将在调用生成器时使用调用它的上下文:

co.call( this, function*() {
    this.loggingService.debug('test');
});
于 2016-01-05T17:52:14.357 回答
0

使用.bind(this)应该工作:

(function() {
  return this === function*() {
    return this; // global object or undefined
  }().next().value;
}).call({}); // false :(
(function() {
  return this === function*() {
    return this; // outer this
  }.bind(this)().next().value;
}).call({}); // true :)
于 2016-01-05T17:52:05.970 回答