0

I have two functions with same names. One inside child class and one inside parent.

I thought If i call method in parent class that parent's function will be invoked.

But it looks it doesn't work like this and invokes child function.

So my question is how to invoke parent function in parent class if i have another with same name in child class.

I would like to get 'Parent' and 'Child', but i get 2 times 'Child'

class Parent {
  constructor() {
    this.init()
  }
  init() {
    console.log('Parent');
  }
}
class Child extends Parent {
  constructor() {
    super();
    this.init()
  }
  init() {
    console.log('Child');
  }
}
new Child();

2 Answers2

0

this is referring to the child instance, and inherits its .init method that shadows the .init method inherited from the parent. To refer to that explicitly, you'd write

class Parent {
  constructor() {
    Parent.prototype.init.call(this)
  }
  init() {
    console.log('Parent');
  }
}

But this is a really bad idea, both to override a method where the overriding one shouldn't be called, and in general to call overrideable methods in the constructor. In your case, just do all your work inside your constructor instead and drop the init method altogether.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

As parent constructor call init() already, child constructor should not call init() any more.

Instead, child init() can optionally call parent init().

cursorrux
  • 1,382
  • 4
  • 9
  • 20