π JavaScript Prototypes
In JavaScript, every object has a hidden internal property called [[Prototype]]
which can be accessed using __proto__
or more reliably through Object.getPrototypeOf()
. Prototypes allow objects to share properties and methods.
π What is a Prototype?
Think of prototypes as inheritance in JavaScript. When you try to access a property or method on an object, JavaScript will look at the object first. If it doesn't find it, it goes up the prototype chain.
π οΈ Constructor Function and Prototype
function Person(name) {
this.name = name;
}
// Adding method to prototype
Person.prototype.greet = function() {
console.log("Hi, Iβm " + this.name);
};
const john = new Person("John");
john.greet(); // "Hi, Iβm John"
π Prototype Chain Example
console.log(john.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true
π Using Object.create()
You can also manually create objects with a specific prototype using Object.create()
.
const animal = {
speak() {
console.log("I can speak");
}
};
const dog = Object.create(animal);
dog.speak(); // "I can speak"
π§ Summary
- All JavaScript objects have a prototype.
- Methods and properties can be added to constructor functionβs prototype.
- Prototype chain enables inheritance.
- Use
Object.create()
to set prototypes manually.
π‘ Tip: Understanding prototypes helps in debugging, memory optimization, and writing reusable object-oriented code.