How to Call a Parent Method from Child Class in JavaScript

How to call a parent method from child class in javascript?

Here's how its done: ParentClass.prototype.myMethod();

Or if you want to call it in the context of the current instance, you can do:
ParentClass.prototype.myMethod.call(this)

Same goes for calling a parent method from child class with arguments:
ParentClass.prototype.myMethod.call(this, arg1, arg2, ..) * Hint: use apply() instead of call() to pass arguments as an array.

How to call a parent class method inside a child class method of the same name?

 super.update();

isn't that super? That will look up the update function in the superclass, and call it with the correct this.

Call a child method from a parent class in ES6

Is it a good practice to call a child method from a parent class?

Yes, it's a totally normal practise. The parent class just calls some method of the instance, and if the child class has overridden the method then the child method is called. However, you usually wouldn't do such a "has my instance defined this method" test, you just would call it. If you want to do nothing by default, just define an empty method (like in @scipper's answer). If you want to make the method abstract (force child classes to override it), you can either leave it undefined or define a method that throws an appropriate exception.

Is is a bad practice to call a child method from a parent constructor?

Yes. Don't do that. (It's a problem in all languages).

The purpose of a constructor is to initialise the instance and nothing else. Leave the invocations of side effects to the caller. This will ensure that all child constructors will finish their initialisation as well.

A contrived example:

class Parent {
autoPlay() {
this.play("automatically "); // call child method
}
play(x) {
console.log(x+"playing default from "+this.constructor.name);
}
}

class ChildA extends Parent {
// does not override play
}
class ChildB extends Parent {
constructor(song) {
super();
this.song = song;
}
play(x) {
console.log(x+"playing "+this.song+" from ChildB");
}
}

const child1 = new ChildA();
child1.autoPlay();
const child2 = new ChildB("'Yeah'");
child2.autoPlay();

Notice how that would not work if the Parent constructor did call autoplay. If you don't like to need an extra method call everywhere after the instantiation, use a helper function. It might even be a static method:

class Parent {
autoPlay() { … }
play { … }
static createAndAutoPlay(...args) {
const instance = new this(...args);
instance.autoPlay();
return instance;
}
}

const child1 = ChildA.createAndAutoPlay();
const child2 = ChildB.createAndAutoPlay("'Yeah'");

Is it possible to call an overridden method in an instance of child class ES 2015?

It's JavaScript, so you can. There's no classes anyway, just prototypal inheritance with some syntactic sugar over it.

Which one do you want to call: Car's emitsCarbon specifically? That'll be

Car.prototype.emitsCarbon.call(car1);

Your object's class' direct ancestor class' emitsCarbon in general?

car1.__proto__.__proto__.emitsCarbon.call(car1);

(You're not supposed to directly access __proto__, but there's nothing actually stopping you besides the general good practice and guidelines).

Also, hybrids do emit carbon. Just a side note.

Call child method from parent class Javascript

Is it a good practice to call child method from a parent class?

Yes, this is totally normal. However, your base class should either provide a default implementation for constructHtml, or declare it as abstract (in TypeScript). To be precise, it is only a good practice to call methods declared on the class itself, although they might be (or even expected to be) overridden in a subclass.

the call to this.constructHtml() returns undefined

That's because you have a return; statement doesn't return anything. Remove the linebreak. Don't use Allman brace style in JavaScript.

How can we invoke the parent's method, when a child has a method with the same name in JavaScript? Anything like type casting in Java here?

The methods inside the class get added to Parent.prototype. So, you could call the Parent's present function with the child object as this

Parent.prototype.present.call(child)

Here's a snippet:

class Parent {
constructor(x) {
this.x = x;
}

present() {
return `I have a ${this.x}`;
}
}

class Child extends Parent {
constructor(x, y) {
super(x);
this.y = y;
}

present() {
return `${super.present()}, it is a ${this.y}`;
}
}

const child = new Child("Tinggu", "Winggu");
console.log(
Parent.prototype.present.call(child)
);

Calling constructor of parent class in static method of child class

super is only callable within the constructor function of a class.

Two answers for you:

  1. The question you actually asked.

  2. What I think you should do instead. :-)

Answering the question you asked:

JavaScript is very special in this regard: this has meaning in static methods (as long as you call them correctly, e.g. TodoV2.addTodo("title")): it's the constructor function you called the static method on. And a subclass constructor function inherits from its superclass constructor function (yes, really). So you can access the constructor function for the parent class using Object.getPrototypeOf(this) in the static method:

// This is something unusual that JavaScript actually does support
static addTodo(title) {
const ctor = Object.getPrototypeOf(this);
return new ctor(title);
}

To handle the case where the user may have called addTodo in a way that doesn't set this, you might do something like this to default to TodoV2 if this is undefined:

static addTodo(title) {
const ctor = Object.getPrototypeOf(this ?? TodoV2);
return new ctor(title);
}

What I think you should do instead

You shouldn't be using a static method for this. Instead, define a constructor for TodoV2:

class TodoV2 extends Todo {
constructor(title, description) {
super(title);
this.description = description ?? "";
}

static addTodo(title) { // Why no `description`?
return new this(title); // Or `new TodoV2(title)`
}
}

You might also look into the Symbol.species pattern if you want subclasses to create instances of superclasses.

How to call Parent method inside Child constructor Javascript ES6-classes?

Try this:

class Foo{
constructor() {
this.classMethod = () => {
console.log('In Foo');
};
}
}

class Bar extends Foo{
constructor() {
super();
const originalClassMethod = this.classMethod.bind(this);
this.classMethod = () => {
console.log('In Bar');
originalClassMethod();
};
}
}

bar = new Bar();
bar.classMethod();

There is an important difference between your first snipped and your second one. Notice that if you define a class like this:

class Foo {
someMethod() {
return 'foo';
}
}

Then if in the console you type: Foo.prototype.someMethod you will have accesss to that method. However, that method can not be bound to any instance because you have not used the new keyword yet, right?

However, if you define a class like this:

class Foo {
constructor() {
this.someMethod = () => 'foo';
}
}

That will not longer be the case, because in the second example, the property someMethod is defined on the instance of the class when the class is being instantiated.

ES6 call parent function from inherited class

You can't have a data property and a method with the same name as you do with getMarketsUrl. They occupy the same property slot on the object. Change the name of one of them.

When you're trying to execute the method, the interpreter is finding the data property first and thus you can't call the method in the normal way.


In addition, you should not be using super to just call a non-overriden method on the object. For example, change this:

buildGetMarketTickerUrl(symbol) {
return super.getMarketDataBaseUrl() + "?"
+ super.buildQueryUrl({marketName: this.buildSymbolParam(symbol),
tickInterval: super.getIntervalParam()})
}

to this:

buildGetMarketTickerUrl(symbol) {
return this.getMarketDataBaseUrl() + "?"
+ this.buildQueryUrl({marketName: this.buildSymbolParam(symbol),
tickInterval: this.getIntervalParam()})
}


Related Topics



Leave a reply



Submit