What is class inheritance in Javascript?

Overview

Classes in Javascript are templates used to create objects.

Example 1

Error: Code Widget Crashed, Please Contact Support

Explanation

  • Lines 2–7: We create the Game class.
  • Lines 10–11: We create new objects using the Game class.
  • Lines 13–14: We print the names of the new objects.

Class inheritance

Class inheritance in Javascript lets us create a new class as the child of another class (the parent). This allows code to be more efficient and concise. This is because we can reuse previously-created class elements in a new class without having to rewrite the same code.

Game class passes on its properties to children classes

Syntax

Class inheritance utilizes two keywords: extends and super.

  • The extends keyword signals that the new class is inheriting the properties of the parent class.

  • The super keyword signals that the enclosed property or method is being inherited from the parent class.

Example 2

//Game class
class Game {
constructor(name, maxNumberOfPlayers) {
this.name = name;
this.maxNumberOfPlayers = maxNumberOfPlayers;
}
}
//The Videogame class inherits properties from the Game class
class Videogame extends Game {
constructor(name, maxNumberOfPlayers, platforms) {
super(name, maxNumberOfPlayers);
this.platforms = platforms;
}
}
//Creates two new videogame objects
let newVideogame1 = new Videogame("The Legend of Zelda: Breath of the Wild", 1, ["Nintendo Switch"]);
let newVideogame2 = new Videogame("Stardew Valley", 4, ["PC", "Nintendo Switch", "Android", "PS", "XBOX"]);
console.log(newVideogame1.name);
//Prints The Legend of Zelda: Breath of the Wild
newVideogame2.platforms.forEach((p) => {
console.log(p)
})
//Prints:
//PC
//Nintendo Switch
//Android
//PS
//XBOX
A class called Videogame inherits the properties from the Game class

Explanation

  • Lines 2–7: We create the Game class.
  • Lines 9–14: We use Javascript inheritance to create a new Videogame class with properties from the Game class.
  • Lines 16–17: We create objects using the Videogame class.
  • Lines 19–23: We print the properties of the new objects.

Free Resources