Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript parent class is calling derived function

I have got a base class and a derived one, each has init function.

When i construct the derived one i want it to:

  1. call its base constructor which:

    1.1. calls its init function

  2. call its own(derived) init function.

The problem is that the derived init function is called twice.

Code:

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 ();

Output:

Derived init
Derived init
like image 690
Dorad Avatar asked Feb 16 '15 12:02

Dorad


2 Answers

In case, we want base init() to be called and then child init() we can solve it like this:

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

Check the example here

Solution when firstly child and then base should be like this.

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

A working example is in this playground. Click the RUN to see two buttons generated

If we want just our derived stuff to be used, we do not have to call init again:

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

This example just uses the child stuff

like image 135
Radim Köhler Avatar answered Oct 19 '22 23:10

Radim Köhler


Another approach could be this (using also Radim's playground example) :

   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 ();

By calling the ancestor's init function from the derived class you can get the wanted flow.

Consider the anscestor's init a virtual method that gets overridden in the derived class(-es).

Playground Example

like image 33
Yiorgos Avatar answered Oct 19 '22 23:10

Yiorgos