typescript父类正在调用派生函数

时间:2015-02-16 12:36:07

标签: oop inheritance typescript

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

当我构建派生的那个时我想要它:

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

    1.1。调用其init函数

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

  3. 问题是派生的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 ();
    

    输出:

    Derived init
    Derived init
    

2 个答案:

答案 0 :(得分:4)

另一种方法可能是这个(使用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 ();

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

考虑anscestor的init是一个在派生类(-es)中被覆盖的虚方法。

Playground Example

答案 1 :(得分:3)

如果我们想要调用基础init(),然后我们可以像子init()那样解决它:

constructor() {
    super.init();
    super();        
}

检查example here

解决方案,首先是孩子,然后是基地应该是这样的。

constructor() {
    super();
    //this.init();
    super.init();
}

一个工作示例位于this playground。单击“运行”以查看生成的两个按钮

如果我们只想使用我们的派生资料,我们不必再次致电init

constructor() {
    super();
    //this.init();
    // init will be called in super
}

此示例仅使用child stuff