I have got a base class and a derived one, each has init function.
When i construct the derived one i want it to:
call its base constructor which:
1.1. calls its init function
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With