English
JavaScript uses a concept called prototype for object-oriented programming. It allows you to create new objects that inherit properties and methods from existing objects. Think of it like a family tree, where child objects inherit characteristics from their parent objects.
In JavaScript, every object has a prototype, which is essentially a reference to another object. When you access a property or method on an object, JavaScript first looks for it on that object. If it doesn't find it there, it searches in the object's prototype, and so on, until it reaches the root prototype called Object.prototype.
Let's look at an example in JavaScript:
// Parent object
var animal = {
makeSound: function() {
console.log("Some generic sound");
}
};
// Child object inheriting from the parent
var cat = Object.create(animal);
// Adding a specific method to the child object
cat.meow = function() {
console.log("Meow!");
};
// Now, cat inherits makeSound from animal
cat.makeSound(); // Outputs: Some generic sound
cat.meow(); // Outputs: Meow!
In this example, the cat object inherits the makeSound method from the animal object through the prototype chain.
Hindi
JavaScript mein prototype naam ka ek concept istemal hota hai object-oriented programming ke liye. Isse aap naye objects create kar sakte hain jo existing objects se properties aur methods inherit karte hain. Isse ek family tree ki tarah samjha ja sakta hai, jahan child objects parent objects se characteristics inherit karte hain.
JavaScript mein har object ka ek prototype hota hai, jo basically doosre object ka ek reference hota hai. Jab aap ek object par property ya method access karte hain, to JavaScript pehle us object par dekhta hai. Agar wahin par nahi milta, to wah us object ke prototype par dekhta hai, aur isi tarah se root prototype Object.prototype tak jata hai.
Chaliye JavaScript mein ek udaharan dekhte hain:
// Parent object
var animal = {
makeSound: function() {
console.log("Kuch generic awaaz");
}
};
// Child object, jo parent se inherit karta hai
var cat = Object.create(animal);
// Child object mein ek specific method add kiya gaya hai
cat.meow = function() {
console.log("Meow!");
};
// Ab, cat animal se makeSound inherit karta hai
cat.makeSound(); // Output: Kuch generic awaaz
cat.meow(); // Output: Meow!
Is udaharan mein, cat object animal object se prototype chain ke zariye makeSound method ko inherit karta hai.
Top comments (0)