0

我想做这个:

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”。我怎样才能使我的代码工作?

请帮忙。谢谢

4

1 回答 1

4

问题是,activate()被调用的时刻this.myService尚未确定。

这是调用堆栈:

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();
    }
}
于 2015-11-27T15:34:11.273 回答