Prototypes & Inheritance
Har JavaScript object ka ek "prototype" hota hai — ek doosra object jisse wo properties/methods "inherit" karta hai. ES6 classes (jo humne pehle dekha) underneath prototypes hi use karte hain — "cleaner syntax" hai, lekin mechanism SAME hai. __proto__ (ya Object.getPrototypeOf()) se prototype chain dekh sakte ho.
const animal = {
eat() { console.log("Eating..."); }
};
const dog = Object.create(animal); // dog ka prototype = animal
dog.bark = function() { console.log("Woof!"); };
dog.bark(); // "Woof!" — apni khud ki property
dog.eat(); // "Eating..." — PROTOTYPE se inherited!
console.log(dog.hasOwnProperty("bark")); // true — khud ki
console.log(dog.hasOwnProperty("eat")); // false — prototype se aayi
// Array/string methods bhi ISI mechanism se aate hain:
console.log([1,2,3].map); // ye Array.prototype se aata hai, har array ke saath nahi banta- Har object ka prototype hai — inherited properties/methods ka source
- ES6 class underneath prototypes use karta hai (syntactic sugar)
- Array methods (map/filter) Array.prototype se aate hain, duplicate nahi hote per-array
Jab ek property access karte ho jo object mein khud nahi hai, JavaScript ENTIRE prototype chain search karta hai jab tak mile na jaaye — deeply nested prototype chains (rare, lekin possible) lookup ko thoda slow kar sakte hain.
const grandparent = { level: "grandparent" };
const parent = Object.create(grandparent);
const child = Object.create(parent);
console.log(child.level); // "grandparent" — 2 levels chain search karta hai
// child -> parent (nahi mila) -> grandparent (mil gaya!)Object.create(null) ek object banata hai jiska KOI prototype hi nahi hai — even basic methods (toString, hasOwnProperty) bhi nahi hote. Pure "dictionary" use-cases ke liye kabhi-kabhi use hota hai, prototype pollution se bachने ke liye.
const normalObj = {};
console.log(normalObj.toString); // function — Object.prototype se aaya
const pureObj = Object.create(null);
console.log(pureObj.toString); // undefined — koi prototype hi nahi hai