【问题标题】:typescript parent class is calling derived function打字稿父类正在调用派生函数
【发布时间】:2015-04-16 23:21:36
【问题描述】:

我有一个基类和一个派生类,每个都有初始化函数。

当我构造派生的时,我想要它:

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

    1.1。调用它的初始化函数

  2. 调用它自己的(派生的)初始化函数。

问题是派生的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

【问题讨论】:

  • init 被覆盖了,这就是它的全部意义......在派生中,你可以做一些像 base.init() 或 super.init() 这样的事情。我不知道 typescript 关键字 - 无论如何你必须明确调用 Base 方法。然而,虽然从理论上讲这将是一个糟糕的设计恕我直言

标签: oop inheritance typescript


【解决方案1】:

另一种方法可能是这样(也使用 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函数,你可以获得想要的流程。

认为祖先的 init 是一个在派生类 (-es) 中被覆盖的虚拟方法。

Playground Example

【讨论】:

    【解决方案2】:

    如果我们希望调用基类init(),然后调用子类init(),我们可以这样解决:

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

    查看example here

    先子后基的解决方法应该是这样的。

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

    this playground 中有一个工作示例。点击RUN查看生成的两个按钮

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

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

    这个例子只使用了child stuff

    【讨论】:

    • 对不起,我没有提到,但我希望顺序是 1.parent.init,2.derived.init。
    • 有道理,然后打电话给super.init(); super(); ;) ;)。我还扩展了我的答案并添加了另一个示例...
    猜你喜欢
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2020-02-22
    相关资源
    最近更新 更多