javascript - 在 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;
它工作正常!这是为什么?我错过了什么?
解决方案
类字段在构造函数之后立即运行,在任何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();
}
推荐阅读
- java - Java 控制台应用程序:如何暂停扫描程序以进行 Sysout 调用
- c - 如何消除全局变量的使用
- javascript - GitHub 部署后 JavaScript 无法正常工作
- c# - 如果异步方法不使用 await 会发生什么?
- sql - 使用 IN a where 使用 case 语句
- java - 如何在 Android 中使用 Google Drive API 更新文件夹?
- c++ - BatchNormalization 层构建
- sql-server - SSAS 的可编程性如何?
- python - 如何创建两个矩形之间发生碰撞的矩形
- python - 对df中的唯一值执行分组计数的有效方法