首页 > 解决方案 > 在 ES6 中委托类方法时出错

问题描述

我有这个 UseCase 类:

class UseCase {

    constructor(repository) {
        this.repository = repository;
    }

    execute() {
      //do stuff
    }

}

module.exports = UseCase;

这个服务类:

class Service {

    constructor(repository) {
        this.useCase = new UseCase(repository);
    }

    doWork = this.useCase.execute;

}

module.exports = Service;

我想要的是委托service.doWork()调用useCase.execute(),但是当我执行它时,我收到了这个错误:

TypeError:无法读取未定义的属性“执行”

但是,如果我将Service代码更改为:

class Service {

    constructor(repository) {
        this.repository = repository;
    }

    doWork = new UseCase(this.repository).execute;

}

module.exports = Service;

它工作正常!这是为什么?我错过了什么?

标签: javascriptecmascript-6es6-class

解决方案


类字段在构造函数之后立即运行,在任何super调用(如果有)之后立即运行。您的代码相当于:

class Service {
    constructor(repository) {
        this.doWork = this.useCase.execute;
        this.useCase = new UseCase(repository);
    }
}

它没有及时定义。

而是doWork在分配给useCase.

您还需要确保.execute使用正确的调用上下文调用它 - 只是传递this.useCase.execute会丢失useCase.

class Service {
    constructor(repository) {
        this.useCase = new UseCase(repository);
        this.doWork = () => this.useCase.execute();
    }
}

您还可以使用在调用时调用的类字段.execute

class Service {
    constructor(repository) {
        this.useCase = new UseCase(repository);
    }
    doWork = () => this.useCase.execute();
}

推荐阅读