Languages
[Edit]
EN

JavaScript - extend class

3 points
Created by:
Dirask Community
6300

In this article, we would like to show you how to extend a class using extends keyword or prototype property in JavaScript.

Quick solution:

class ChildClass extends ParentClass {
  //...
}

or:

ChildClass.prototype = new ParentClass();

 

Practical example

Let's say we have class Animal and assume as a general rule that every animal can move. We want to create a new class based on Animal class but extended with new functionalities.

The second class we create is the Dog class based on Animal. It has all the fields and methods of the Animal class, additionally extended with the bark() method.

When we create an instance of a Dog class, we can use both Dog and Animal class methods.

Runnable example:

// ONLINE-RUNNER:browser;

class Animal {
  move() {
    console.log('The animal moves...');
  }
}

class Dog extends Animal {
  bark() {
    console.log('The dog barks...');
  }
}

const Labrador = new Dog();
Labrador.bark();  // The dog barks...
Labrador.move();  // The animal moves...

Prototype-based class extending

In this section, we show how to extend some class using prototype property. 

// ONLINE-RUNNER:browser;

function Animal() {
  this.move = function() {
    console.log('The animal moves...');
  };
}

function Dog() {
  this.bark = function() {
    console.log('The dog barks...');
  };
}

Dog.prototype = new Animal();

const Labrador = new Dog();
Labrador.bark();  // The dog barks...
Labrador.move();  // The animal moves...

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join