Prototypes & OOPmedium

Explain prototypal inheritance

How does the prototype chain work in JavaScript? Implement inheritance using both the classic prototype pattern and ES6 classes.

Asked at Google, Amazon

#prototype#inheritance#classes#__proto__

Answer

// Usage
// Use inheritance for shared behavior and polymorphism.
// Every object has a [[Prototype]] link to another object.
// Property lookup walks up the chain until null is reached.

// ── ES6 classes (syntactic sugar over prototypes) ──
class Animal {
  constructor(name) { this.name = name }
  speak() { return `${this.name} makes a noise.` }
}

class Dog extends Animal {
  speak() { return `${this.name} barks.` }
}

const d = new Dog('Rex')
d.speak()              // "Rex barks."
d instanceof Dog       // true
d instanceof Animal    // true

// ── Same thing with raw prototypes ──
function Animal(name) { this.name = name }
Animal.prototype.speak = function() {
  return `${this.name} makes a noise.`
}

function Dog(name) { Animal.call(this, name) }
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.constructor = Dog
Dog.prototype.speak = function() {
  return `${this.name} barks.`
}

// ── Object.create for pure prototype chains ──
const animal = { speak() { return 'noise' } }
const dog = Object.create(animal)
dog.speak() // "noise" — found on animal via prototype chain

Practise more Prototypes & OOP questions →