In JavaScript, every object has an internal link to another object called its prototype. This prototype object can have its own prototype, and so on — forming a prototype chain.
Example:
function Person(name) {
this.name = name; // This is a property specific to each instance
}
// Adding method to prototype
Person.prototype.sayHello = function () {
console.log(`Hello, I'm ${this.name}`);
};
// Create a new instance
const john = new Person('John');
const jane = new Person('Jane');
john has a property name = 'John'.
jane has a property name = 'Jane'.
Both john and jane share the same sayHello method that is defined on the Person.prototype
Save memory without creating same function twice
---
john.sayHi = function () {
console.log(`Hello, I'm ${this.name}`);
};
Here, we're overriding the sayHi method specifically for john.
This creates a new function that only john can access.
It does not affect other instances like jane,
who will still use the method defined on Person.prototype.sayHello