Categories
JavaScript Answers

How to override methods with JavaScript?

Spread the love

Sometimes, we want to override methods with JavaScript.

In this article, we’ll look at how to override methods with JavaScript.

How to override methods with JavaScript?

To override methods with JavaScript, we can use the class syntax.

For instance, we write

class A {
  speak() {
    console.log("I'm A");
  }
}

class B extends A {
  speak() {
    super.speak();
    console.log("I'm B");
  }
}

const a = new A();
a.speak();

const b = new B();
b.speak();

to create class B that inherits from class A.

In it, we override class A‘s speak method by calling super.speak.

Then we add our own behavior for the speak method exclusive to B.

Therefore, when we call a.speak, we get "I'm A".

And when we call b.speak, we get "I'm B".

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *