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 animalHow 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 chainClass 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 -> nullChecking the chain
js
d instanceof Dog; // true
d instanceof Animal; // true
Object.getPrototypeOf(d) === Dog.prototype; // trueJavaScript
classis syntactic sugar - under the hood it still uses prototype chains. Understanding this helps debug unexpected behavior withthisand inheritance.
updated
did you know it?