我想这样做:
export abstract class Base{
constructor(){
this.activate();
}
protected abstract activate():void;
}
class MyClass extends Base{
static $inject = ['myService'];
constructor(service: myService){
super();
this.myService = myService;
}
activate():void{
this.myService.doSomething();
}
}
但我不能,因为派生类方法中的'this'类型是'Base'。 我如何使我的代码工作?
请帮忙。 感谢
答案 0 :(得分:4)
问题在于,activate()
被调用的那一刻,this.myService
尚未设置。
这是callstack:
MyClass::constructor() -> super() -> Base::constructor() -> MyClass::activate()
因此,在MyClass
的构造函数中,您需要在调用基础构造函数之前分配this.myService
:
class MyClass extends Base{
static $inject = ['myService'];
constructor(service: myService){
this.myService = myService; // <-- before super();
super();
}
activate():void{
this.myService.doSomething();
}
}