What is class inheritance in Javascript?
Overview
Classes in Javascript are templates used to create objects.
Example 1
//Creating a classclass Game {constructor(name, maxNumberOfPlayers) {this.name = name;this.maxNumberOfPlayers = maxNumberOfPlayers;}}//Using a classlet newGame = new Game("Monopoly", 8)let newGame2 = new Game("UNO", 10)console.log(newGame.name)console.log(newGame2.name)//Prints://Monopoly//UNO
Explanation
- Lines 2–7: We create the
Gameclass. - Lines 10–11: We create new objects using the
Gameclass. - 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.
Syntax
Class inheritance utilizes two keywords: extends and super.
-
The
extendskeyword signals that the new class is inheriting the properties of the parent class. -
The
superkeyword signals that the enclosed property or method is being inherited from the parent class.
Example 2
//Game classclass Game {constructor(name, maxNumberOfPlayers) {this.name = name;this.maxNumberOfPlayers = maxNumberOfPlayers;}}//The Videogame class inherits properties from the Game classclass Videogame extends Game {constructor(name, maxNumberOfPlayers, platforms) {super(name, maxNumberOfPlayers);this.platforms = platforms;}}//Creates two new videogame objectslet 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 WildnewVideogame2.platforms.forEach((p) => {console.log(p)})//Prints://PC//Nintendo Switch//Android//PS//XBOX
Explanation
- Lines 2–7: We create the
Gameclass. - Lines 9–14: We use Javascript inheritance to create a new
Videogameclass with properties from theGameclass. - Lines 16–17: We create objects using the
Videogameclass. - Lines 19–23: We print the properties of the new objects.