Prototype
In JavaScript, every object has an internal hidden property called [[Prototype]] (often accessed using __proto__ or through Object.getPrototypeOf()).
- This prototype is a reference to another object.
- The prototype object can have its own properties and methods.
- When you try to access a property or method on an object, JavaScript first looks at the object itself.
- If it doesn’t find it, it looks at the object’s prototype.
- If not found there, it goes further up the prototype chain until it reaches
null.
👉 Example:
let person = {
greet: function() {
console.log("Hello!");
}
};
let student = Object.create(person); // student’s prototype is person
student.name = "John";
student.greet(); // "Hello!" (inherited from prototype)
Here:
studentdoesn’t have agreetmethod.- JavaScript looks at
student.__proto__(which isperson) and findsgreet.
Prototypal Inheritance
Prototypal inheritance is the mechanism by which one object can inherit properties and methods from another object via its prototype.
Key points:
- Objects can serve as prototypes for other objects.
- This allows property/method sharing without duplication.
- It forms a chain known as the prototype chain.
👉 Example with constructor functions:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + " makes a noise.");
};
let dog = new Animal("Dog");
dog.speak(); // "Dog makes a noise."
Here:
Animal.prototypehas thespeakmethod.dogdoesn’t havespeakdirectly, but it inherits it via its prototype.
✅ In short:
- Prototype = the object that provides a fallback for another object’s properties.
- Prototypal Inheritance = the process where objects inherit properties/methods from other objects via the prototype chain.
