8

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
1
  • init is overwritten that's what it's all about ... In derived can you do sth like base.init() or super.init(). I do not know the typescript keyword - anyways you have to call the Base method explictly. However while theoratically interestang this would be a bad design IMHO Commented Feb 16, 2015 at 12:43

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I did not mention, but i wanted the order to be 1.parent.init,2.derived.init.
Make sense, then just call super.init(); super(); ;) ;). I also extended my answer and added another example...
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.