Prototypes & Prototype Chain Kya Hota Hai?
JavaScript me inheritance aur object connection ke core concept ko samjhein.
Prototype Kya Hai?
JavaScript mein, prototype ek internal object hota hai jo doosre objects ke saath juda hota hai. Yeh feature JavaScript ko inheritance achieve karne me madad karta hai. Har object ke paas ek hidden property `[[Prototype]]` hoti hai jo uske prototype object ko point karti hai.
let person = {
name: "Ravi",
greet: function () {
console.log("Hello!");
}
};
console.log(person.toString()); // Output: "[object Object]"
Yahan `toString()` method `person` object me define nahi hai, lekin yeh fir bhi kaam kar raha hai. Aisa isliye kyunki `person` ka prototype `Object.prototype` hai, jahan `toString()` method already defined hai.
Prototype Chain Kya Hai?
Jab aap kisi object ki property access karte hain, toh JavaScript sabse pehle uss object me property dhundhta hai. Agar wahan nahi milti, toh woh uske prototype me search karta hai. Agar wahan bhi nahi milti, toh woh uss prototype ke prototype me search karta hai. Yeh process tab tak chalta hai jab tak property mil na jaaye ya chain `null` par khatm na ho jaaye. Isi series of linked prototypes ko Prototype Chain kehte hain.
Chain aamtaur par aisi dikhti hai: `myObject` → `Array.prototype` → `Object.prototype` → `null`.
Constructor Functions and Prototypes
Constructor functions ka use karke hum ek blueprint se multiple objects bana sakte hain. Inke `prototype` property ka use karke hum common methods aur properties define kar sakte hain jo sabhi instances share karenge. Isse memory save hoti hai.
Efficient Way (Using Prototype)
function Person(name) {
this.name = name;
}
// Method ko prototype par define karna
Person.prototype.sayHello = function () {
console.log("Hi, I’m " + this.name);
};
let user1 = new Person("Amit");
let user2 = new Person("Priya");
user1.sayHello(); // Output: Hi, I’m Amit
user2.sayHello(); // Output: Hi, I’m Priya
Yahan, `sayHello` method dono instances (`user1`, `user2`) ke liye memory me ek hi baar store hota hai.
Key Takeaways
- JavaScript me inheritance prototypes ke through achieve hoti hai.
- Har object ke paas ek hidden link `[[Prototype]]` hota hai jo uske prototype ko point karta hai.
- Prototype Chain ek lookup mechanism hai jisse properties aur methods ko parent objects se inherit kiya jaata hai.
- Constructor functions ke `prototype` property par methods define karna memory-efficient hota hai.
Ek `Car` constructor function banayein aur `drive` method ko uske prototype par add karein. Fir do alag-alag car instances banakar `drive` method call karein.
Practice in JS EditorApni knowledge test karne ke liye is quick quiz ko dein.
Start Quiz