Skip to main content
05

How does prototypal inheritance work?

MediumJavaScriptPrototypesOOP

How does prototypal inheritance work in JavaScript, and what does class do under the hood?

TL;DR

Every object has a hidden link, [[Prototype]], to another object. When you read a property that isn't on the object itself, JavaScript walks up this prototype chain until it finds the property or reaches null. class is mostly syntax over this mechanism: methods live on Class.prototype, and every instance links to it.

Key points

  • Methods are shared, not copied: all instances use the single function on the prototype.
  • new Fn() creates an object, links its [[Prototype]] to Fn.prototype, runs Fn with this bound to it, and returns it.
  • extends links Child.prototype to Parent.prototype, and super() runs the parent constructor.
  • Reading walks the chain; writing always creates an own property on the object (shadowing).
  • Read or set the link with Object.getPrototypeOf and Object.create(proto). Avoid __proto__.

Example

js
class Animal {
  constructor(name) {
    this.name = name
  }
  speak() {
    return `${this.name} makes a sound`
  }
}
class Dog extends Animal {
  speak() {
    return `${this.name} barks`
  }
}

const rex = new Dog('Rex')
rex.speak() // 'Rex barks'
Object.getPrototypeOf(rex) === Dog.prototype // true
Object.getPrototypeOf(Dog.prototype) === Animal.prototype // true
rex.hasOwnProperty('speak') // false: it lives on the prototype

Common follow-ups

  • prototype vs [[Prototype]]? Fn.prototype is the object that instances created by new Fn() will link to. [[Prototype]] is each object's own link.
  • Is class exactly the same as a constructor function? Almost. Classes run in strict mode, can't be called without new, and their methods aren't enumerable.

What interviewers look for

Tip

Explain property lookup up the chain, shared methods on the prototype, and class as sugar over it.

  • Red flag: thinking JavaScript classes copy methods into each instance like classical OOP.

Was this helpful?

Related questions