Prototypal inheritance is a mechanism in JavaScript where objects inherit properties and methods from other objects. Instead of classes (like in classical OOP), JS uses prototypes to share behavior.
🔹 How It Works
- Every JavaScript object has an internal link to another object called its prototype (
__proto__in old JS orObject.getPrototypeOf()in modern JS). - When you try to access a property on an object:
- JS first looks at the object itself.
- If the property is not found, it looks up the prototype chain until it finds the property or reaches
null.
🔹 Example
const animal = {
eat() {
console.log("Eating...");
}
};
const dog = {
bark() {
console.log("Woof!");
}
};
// Set prototype
Object.setPrototypeOf(dog, animal);
dog.bark(); // Woof!
dog.eat(); // Eating... (inherited from animal)
Explanation:
dogdoesn’t haveeat()directly.- JS finds
eat()onanimal, which isdog’s prototype.
🔹 Using Constructor Functions
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, I am ${this.name}`);
};
const p1 = new Person("Teekam");
p1.greet(); // Hello, I am Teekam
- Methods are defined on
Person.prototype→ all instances share the same method. - Efficient memory usage: no need to create a new function per instance.
🔹 ES6 Classes (Syntactic Sugar)
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, I am ${this.name}`);
}
}
class Student extends Person {
study() {
console.log(`${this.name} is studying`);
}
}
const s1 = new Student("Teekam");
s1.greet(); // Hello, I am Teekam
s1.study(); // Teekam is studying
- ES6 classes are syntactic sugar over prototypal inheritance.
- Internally, methods are stored on the prototype.
✅ Key Points
- JS uses objects inheriting from other objects, not classical classes.
- The prototype chain allows property/method sharing.
- Constructors +
.prototypeor ES6 classes can implement inheritance. - Memory-efficient because shared methods live on the prototype.