The extends keyword is used in class declarations and expressions to create a class that acts as a child of another class.
class x extends y {
}
Here, x is the child class and y is the parent class. The extend keyword acts as the link between the two classes. The extends keyword can also connect a class to a built-in object or a subclass (a class inside another class).
Please note that the first class must be the child class and not a parent class or a built-in object.
The Prototype Property
Any constructor with the parent class prototype property can be considered a candidate for the parent property.
Note: The prototype should not be an object or null.
The prototype refers to an object linked to every function and built-in object by default in JavaScript and can be easily accessed and modified but it is not visible.
The super() method
Just as a child in real life inherits the parent's properties, the properties of a parent in JavaScript work the same way.
In this case, the child class inherits all of the parent class's methods.
Why is inheritance in JavaScript necessary?
To avoid repetition of code; inheritance helps with the reusability of code, whereby a class inherits the methods of a parent class as explained above.
The super() method and its relationship with inheritance
The super () method refers to the parent class. It helps get access to the parent‘s properties and methods. In simple words, it helps make inheritance possible. It does this by calling the constructor of the parent class within the child class.
The superKeyword can access properties.
- On an object, literal
- On a class prototype
- Invoke a superclass constructor.
How exactly do the super () method and the extend keyword work in code?
<body>
<p id="task"></p>
<script>
class Pride {
constructor(lion) {
this.name = lion;
}
method() {
return this.name + "is the king of the savannah and "
}
}
// extend keyword
class Cub extends Pride {
constructor(lion, simba) {
// Note: The super() method must be called before the ‘this’ keyword excluding the super() method or using it after the ‘.this’ keyword will result to a reference error
super(lion); //refers to the parentClass
this.cub = simba;
}
answer(){
return this.method() + this.cub + " is his son "
}
}
theKing = new Cub("mufasa " , "simba");
document.getElementById("task").innerHTML = theKing.answer();
</script>
</body>
</html>
Things to note when using the extend keyword
- On the right hand side, you can use any expression that evaluates to a constructor.
// Y is the right-hand side in this case.
x extends y {
}
The extends keyword sets the prototype for both the child class and its prototype. Here it allows the inheritance of the static properties and the prototype properties.
You can use extend with predefined objects like arrays, dates, math, and strings.
To get a full grasp on JavaScript classes please check out my first article on JavaScript classes