JavaScript Class Inheritance
Class inheritance lets a new class take on the properties and methods of an existing class. The new class is the child, and the class it builds on is the parent.
Extend a parent
Model extends Car, so every Model starts with the properties and methods of Car.
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(currentYear) {
return currentYear - this.year;
}
}
class Model extends Car {
constructor(name, year, model) {
super(name, year);
this.model = model;
}
}Use a parent method
The child defines no age method of its own. The call still works, because age is inherited from Car.
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(currentYear) {
return currentYear - this.year;
}
}
class Model extends Car {
constructor(name, year, model) {
super(name, year);
this.model = model;
}
}
const myCar = new Model("Ford", 2020, "Mustang");
console.log(myCar.age(2026));Read a child property
The model property exists only on the child class. The parent class knows nothing about it.
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(currentYear) {
return currentYear - this.year;
}
}
class Model extends Car {
constructor(name, year, model) {
super(name, year);
this.model = model;
}
}
const myCar = new Model("Ford", 2020, "Mustang");
console.log(myCar.model);Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(currentYear) {
return currentYear - this.year;
}
}
class Model extends Car {
constructor(name, year, model) {
super(name, year);
this.model = model;
}
label() {
return this.name + " " + this.model;
}
}
const myCar = new Model("Ford", 2020, "Mustang");
console.log(myCar.age(2026));
console.log(myCar.model);
console.log(myCar.label());Key points
- The extends keyword makes one class the child of another.
- The child inherits the properties and methods of the parent.
- The child constructor calls super to run the parent constructor.
- super must run before the child constructor uses this.
- The child can store extra properties the parent does not have.
- The child can add methods the parent lacks.
In this example, Model inherits the age method from Car and adds a model property of its own. It also adds a label method that the parent does not have. One object uses all three features.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a child class get from its parent class?