Home
← All questions

Inheritance in JavaScript (ES5) and class vs prototypal

MediumPremiumJavaScript

JavaScript interview practice: Implement inheritance in ES5, and convert class-based inheritance to prototypal.

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 own name property.
  • Animal instances have a speak() method returning "<name> makes a noise.".
  • new Dog(name) also gets its own name property, set through the parent's initialization logic rather than duplicated code.
  • Dog instances can call speak() (inherited) and their own bark() method returning "<name> barks!".
  • Methods are shared through the prototype chain, not recreated per instance.
  • A Dog instance must satisfy instanceof Dog and instanceof Animal, and its constructor property must point to Dog.
  • Animal instances must not have bark().
  • 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 extends together with super(...) do under the hood?
  • What breaks if the constructor property is not restored?
  • How would you override speak() in Dog and still call the parent version?
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium