Classes in Javascript are templates used to create objects.
//Creating a class class Game { constructor(name, maxNumberOfPlayers) { this.name = name; this.maxNumberOfPlayers = maxNumberOfPlayers; } } //Using a class let newGame = new Game("Monopoly", 8) let newGame2 = new Game("UNO", 10) console.log(newGame.name) console.log(newGame2.name) //Prints: //Monopoly //UNO
Game
class.Game
class.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.
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.
//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
Game
class.Videogame
class with properties from the Game
class.Videogame
class.RELATED TAGS
CONTRIBUTOR
View all Courses