How do you create a subclass using extends?
Short answer
extends sets up prototype-based inheritance between classes, and super() inside the subclass's constructor calls the parent class's constructor to initialize inherited state before adding subclass-specific properties.
Advertisement
AModel answer
extends sets up prototype-based inheritance between classes, and super() inside the subclass's constructor calls the parent class's constructor to initialize inherited state before adding subclass-specific properties.
class Animal {
constructor(name) { this.name = name; }
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
}Real-world example
Modeling an AdminUser class that extends a base User class with extra permissions.
Likely follow-ups
- Must super() be called before using 'this' in a subclass constructor?
Related topics