Do you know what is JavaScript prototype. Don't worry we'll cover everything, just keep reading techbrushup.
Prototype Chain
If a property or method is not found on the object itself, JavaScript looks for it in the prototype, then the prototype’s prototype, and so on, until it reaches Object.prototype (the root).
Every JavaScript object has an internal link to another object called its prototype. This prototype object can have its own prototype, forming a prototype chain.
Why Use Prototypes?
- Memory efficiency: Methods are stored once in the prototype, not duplicated for each object.
- Inheritance: Enables one object type to inherit methods and properties from another.
prototype.js
// Constructor function
function Person(name) {
this.name = name;
}
// Adding a method to the prototype
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
const alice = new Person("Alice");
const bob = new Person("Bob");
alice.sayHello(); // Hello, my name is Alice
bob.sayHello(); // Hello, my name is Bob
// Both share the same sayHello method from Person.prototype
console.log(alice.sayHello === bob.sayHello); // true