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 に答える