我试图使用显式的.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;
答案 0 :(得分:3)
co将使用调用生成器时调用的上下文:
co.call( this, function*() {
this.loggingService.debug('test');
});
答案 1 :(得分: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 :)