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]]toFn.prototype, runsFnwiththisbound to it, and returns it.extendslinksChild.prototypetoParent.prototype, andsuper()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.getPrototypeOfandObject.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 prototypeCommon follow-ups
prototypevs[[Prototype]]?Fn.prototypeis the object that instances created bynew Fn()will link to.[[Prototype]]is each object's own link.- Is
classexactly the same as a constructor function? Almost. Classes run in strict mode, can't be called withoutnew, 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.