Problem
Interviewers still probe how prototypes work under ES6 classes, and explaining inheritance in JavaScript (ES5) and class vs prototypal inheritance is a staple of frontend rounds, especially when reading older libraries or transpiled output.
Using only ES5 constructor functions (no class keyword), build an Animal constructor and a Dog constructor that inherits from it. Then write the equivalent ES6 class version.
Requirements
new Animal(name)creates an object with its ownnameproperty.Animalinstances have aspeak()method returning"<name> makes a noise.".new Dog(name)also gets its ownnameproperty, set through the parent's initialization logic rather than duplicated code.Doginstances can callspeak()(inherited) and their ownbark()method returning"<name> barks!".- Methods are shared through the prototype chain, not recreated per instance.
- A
Doginstance must satisfyinstanceof Dogandinstanceof Animal, and itsconstructorproperty must point toDog. Animalinstances must not havebark().- The ES6 version must behave identically.
Example
const rex = new Dog("Rex");
rex.speak(); // "Rex makes a noise."
rex.bark(); // "Rex barks!"
rex instanceof Animal; // true
rex.constructor === Dog; // true
"bark" in new Animal("Tom"); // false
Follow-ups
- What does
extendstogether withsuper(...)do under the hood? - What breaks if the
constructorproperty is not restored? - How would you override
speak()inDogand still call the parent version?