JavaScript Interview Question: How Does Prototypal Inheritance Work?
Short answer: every JavaScript object has an internal link to another object, its prototype. When you read a property that the object doesn't have, JavaScript looks it up along this prototype chain until it finds it or reaches null.
const animal = { speak() { return `${this.name} makes a sound`; } };
const dog = Object.create(animal); // dog's prototype is animal
dog.name = 'Rex';
dog.speak(); // 'Rex makes a sound' - found on the prototype
Object.getPrototypeOf(dog) === animal; // true
Classes are built on prototypes
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
speak() { return `${super.speak()}: woof`; }
}
const rex = new Dog('Rex');
Object.getPrototypeOf(rex) === Dog.prototype; // true
Object.getPrototypeOf(Dog.prototype) === Animal.prototype; // true
Methods live once on Dog.prototype and are shared by all instances, not copied into each one.
prototype vs __proto__
Fn.prototype- a property on constructor functions and classes: the object that will become the prototype of instances created withnew Fn().obj.__proto__- the actual prototype link of an object (legacy accessor). PreferObject.getPrototypeOf(obj).
Own vs inherited properties
Object.hasOwn(rex, 'name'); // true - on the instance
Object.hasOwn(rex, 'speak'); // false - inherited
'speak' in rex; // true - in checks the whole chain
Bonus: prototype pollution
Merging untrusted JSON into objects can set __proto__ properties and change the behaviour of every object. Validate input and use Object.create(null) or Map for dictionaries of user keys.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.