Skip to content
javascript questions

JavaScript · 4 of 10middle~1 min

What is prototypal inheritance and how does it work?

#core#oop

Prototypal Inheritance

In JavaScript, objects inherit from other objects through a prototype chain. Every object has an internal [[Prototype]] link to another object.

Prototype chain

js
const animal = { speak() { return `${this.name} makes a sound`; } }; const dog = Object.create(animal); dog.name = 'Rex'; dog.speak(); // 'Rex makes a sound' // dog has no speak() - JS looks up the chain to animal

How property lookup works

text
dog.speak() -> look in dog: not found -> look in animal (dog's prototype): found! -> look in Object.prototype: ... -> null - end of chain

Class syntax (sugar over prototypes)

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 d = new Dog('Rex'); d.speak(); // 'Rex barks' // under the hood: // Dog.prototype -> Animal.prototype -> Object.prototype -> null

Checking the chain

js
d instanceof Dog; // true d instanceof Animal; // true Object.getPrototypeOf(d) === Dog.prototype; // true

JavaScript class is syntactic sugar - under the hood it still uses prototype chains. Understanding this helps debug unexpected behavior with this and inheritance.

updated

did you know it?

related questions