在 ES6 中委派 class 方法时出错
Error when delegating class method in ES6
我有这个用例class:
class UseCase {
constructor(repository) {
this.repository = repository;
}
execute() {
//do stuff
}
}
module.exports = UseCase;
和此服务 class:
class Service {
constructor(repository) {
this.useCase = new UseCase(repository);
}
doWork = this.useCase.execute;
}
module.exports = Service;
我想要的是委托 service.doWork()
调用 useCase.execute()
,但是当我执行它时,我得到这个错误:
TypeError: Cannot read property 'execute' of undefined
但是,如果我将 Service
代码更改为:
class Service {
constructor(repository) {
this.repository = repository;
}
doWork = new UseCase(this.repository).execute;
}
module.exports = Service;
它工作正常!这是为什么?我错过了什么?
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();
}
}
您还可以使用 class 字段,在调用时调用 .execute
:
class Service {
constructor(repository) {
this.useCase = new UseCase(repository);
}
doWork = () => this.useCase.execute();
}
我有这个用例class:
class UseCase {
constructor(repository) {
this.repository = repository;
}
execute() {
//do stuff
}
}
module.exports = UseCase;
和此服务 class:
class Service {
constructor(repository) {
this.useCase = new UseCase(repository);
}
doWork = this.useCase.execute;
}
module.exports = Service;
我想要的是委托 service.doWork()
调用 useCase.execute()
,但是当我执行它时,我得到这个错误:
TypeError: Cannot read property 'execute' of undefined
但是,如果我将 Service
代码更改为:
class Service {
constructor(repository) {
this.repository = repository;
}
doWork = new UseCase(this.repository).execute;
}
module.exports = Service;
它工作正常!这是为什么?我错过了什么?
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();
}
}
您还可以使用 class 字段,在调用时调用 .execute
:
class Service {
constructor(repository) {
this.useCase = new UseCase(repository);
}
doWork = () => this.useCase.execute();
}