Day 28 Prototype Chain
JavaScript mein inheritance prototype chain ke zariye hoti hai. Jab koi property ya method kisi object par nahi milti, JavaScript prototype chain mein upar jaake dhundta hai. Yahi JavaScript inheritance ka core mechanism hai.
Prototype kya hai?
Har JavaScript object ka ek prototype hota hai. Methods aur properties prototype mein share hoti hain.
function Person(name, age) {
this.name = name;
this.age = age;
}
// Prototype par method add karo — sab instances share karenge
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
Person.prototype.isAdult = function() {
return this.age >= 18;
};
let p1 = new Person("Zohaib", 25);
let p2 = new Person("Ali", 15);
console.log(p1.greet()); // Hello, I'm Zohaib
console.log(p1.isAdult()); // true
console.log(p2.isAdult()); // false
// Prototype chain check
console.log(p1.__proto__ === Person.prototype); // true
console.log(p1 instanceof Person); // true
Object.create() — Prototype Inheritance
Object.create(proto) se ek object banao jiska prototype specified object ho.
let animal = {
breathe() { return `${this.name} is breathing`; },
eat(food) { return `${this.name} eats ${food}`; }
};
// dog inherits from animal
let dog = Object.create(animal);
dog.name = "Rex";
dog.bark = function() { return "Woof!"; };
console.log(dog.breathe()); // Rex is breathing — inherited!
console.log(dog.bark()); // Woof! — own method
// Prototype chain: dog → animal → Object.prototype → null
console.log(Object.getPrototypeOf(dog) === animal); // true
// hasOwnProperty — check if property is own (not inherited)
console.log(dog.hasOwnProperty("name")); // true
console.log(dog.hasOwnProperty("breathe")); // false
🎯 Practice Challenge
Vehicle base object banao with start() aur stop() methods. Car aur Motorcycle banao Object.create se. Apne methods bhi add karo.