Prototypal inheritance is the way objects in JavaScript inherit properties and methods from other objects. Unlike classical inheritance, there are no classes here — objects inherit directly from other objects through the proto link.
Prototypal inheritance is the main inheritance mechanism in JavaScript. It’s different from inheritance in other languages that have classes.
Every object can have a prototype — another object from which it inherits properties:
const parent = { name: 'Parent' };
const child = Object.create(parent);
console.log(child.name); // 'Parent' — through prototypeconst obj = {};
console.log(obj.__proto__); // Link to prototype// obj → Object.prototype → null
const obj = {};const animal = {
type: 'animal',
speak() {
console.log('I am ' + this.type);
}
};
const dog = Object.create(animal);
dog.type = 'dog';
dog.speak(); // 'I am dog'const parent = {
greet() { return 'Hello!'; }
};
const child = Object.create(parent);
console.log(child.greet()); // 'Hello!' — method from prototypeconst parent = { name: 'Parent' };
const child = Object.create(parent);
child.age = 25;
console.log(child.age); // 25 — own property
console.log(child.name); // 'Parent' — from prototypeconst parent = { name: 'Parent' };
const child = Object.create(parent);
// Override property
child.name = 'Child';
console.log(child.name); // 'Child' — own value// Base object
const vehicle = {
move() { console.log('Moving'); }
};
// Extend it
const car = Object.create(vehicle);
car.wheels = 4;// Methods in prototype — one copy for all
const parent = {
sharedMethod() { /* logic */ }
};
const obj1 = Object.create(parent);
const obj2 = Object.create(parent);
// Both objects use one method// ❌ Thinking like classes
class Parent {}
class Child extends Parent {}
// ✅ In prototypal inheritance
const parent = {};
const child = Object.create(parent);// ❌ Complex way
const obj = {};
Object.setPrototypeOf(obj, { name: 'New prototype' });
// ✅ Simple way
const parent = { name: 'Prototype' };
const child = Object.create(parent);Prototypal inheritance is a powerful mechanism that underlies all objects in JavaScript.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪