Class inheritance in JavaScript
Level 4229 keystrokes
Dog extends Animal, inheriting its constructor and overriding speak, so new Dog("Max").speak() returns "Max barks" instead of "Max makes a sound".
JavaScript code
// Defines the base class Animal1class Animal { // The constructor runs on new and receives the name2 constructor(name) { // Stores the name on the new instance3 this.name = name;4 } // The base version of speak, used when a subclass does not override it5 speak() { // Returns a generic message built with a template literal6 return `${this.name} makes a sound`;7 }8}// Dog inherits from Animal; with no constructor of its own, it uses Animal's9class Dog extends Animal { // Overrides speak: this version replaces Animal's for Dog instances10 speak() { // this.name was set by the inherited constructor11 return `${this.name} barks`;12 }13}// Creates a Dog; Animal's constructor sets name to "Max"14const dog = new Dog("Max");// Calls the overriding speak and prints Max barks15console.log(dog.speak());Output
Max barks
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
{× 7}× 7(× 6)× 6;× 5.× 5`× 4"× 2=× 2$× 2