typescript父类正在调用派生函数

Dor*_*rad 6 oop inheritance typescript

我有一个基类和一个派生类,每个都有init函数.

当我构建派生的我想要它:

  1. 调用它的基础构造函数:

    1.1.调用它的init函数

  2. 调用它自己的(派生的)init函数.

问题是派生的init函数被调用两次.

码:

class Base{
    constructor() {
        this.init();
    }
    init(){
        console.log("Base init");
    }
}
class Derived extends Base{
    constructor() {
        super();
        this.init();
    }
    init(){
        console.log("Derived init");
    }
}
var obj = new Derived ();
Run Code Online (Sandbox Code Playgroud)

输出:

Derived init
Derived init
Run Code Online (Sandbox Code Playgroud)

Rad*_*ler 5

如果我们希望init()先调用 base,然后再调用 child,init()我们可以这样解决:

constructor() {
    super.init();
    super();        
}
Run Code Online (Sandbox Code Playgroud)

检查这里的例子

首先是子级然后是基础时的解决方案应该是这样的。

constructor() {
    super();
    //this.init();
    super.init();
}
Run Code Online (Sandbox Code Playgroud)

这个游乐场就是一个有效的例子。点击RUN可以看到生成的两个按钮

如果我们只想使用派生的东西,则不必init再次调用:

constructor() {
    super();
    //this.init();
    // init will be called in super
}
Run Code Online (Sandbox Code Playgroud)

这个例子只使用了子元素


小智 5

另一种方法可能是这样的(也使用 Radim 的游乐场示例):

   class Base{
    constructor() {
        this.init();
    }
    init(){
        var button = document.createElement('button');      
        button.textContent = "base init";
        document.body.appendChild(button);
    }
}
class Derived extends Base{
    constructor() {
        super();

    }
    init(){
        super.init();
        var button = document.createElement('button');      
        button.textContent = "Derived init";
        document.body.appendChild(button);
    }
}
var obj = new Derived ();
Run Code Online (Sandbox Code Playgroud)

通过从派生类调用祖先的 init 函数,您可以获得所需的流程。

考虑祖先的 init 是一个在派生类(-es)中被重写的虚拟方法。

游乐场示例