EN
JavaScript - extend class
3
points
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...