【问题标题】:How do I get away from using the `self = this` hack when using ES6 classes and generator functions?在使用 ES6 类和生成器函数时,如何避免使用 `self = this` hack?
【发布时间】:2016-04-09 15:32:48
【问题描述】:

我尝试使用显式的 .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;

【问题讨论】:

    标签: javascript node.js ecmascript-6 co


    【解决方案1】:

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

    co.call( this, function*() {
        this.loggingService.debug('test');
    });
    

    【讨论】:

    • 关于co,这是最正确的答案。
    【解决方案2】:

    使用.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 :)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 2017-11-20
      • 2018-11-02
      相关资源
      最近更新 更多