Prototypes are JavaScript's inheritance mechanism. Every object has a prototype chain that lets it inherit methods.
đ Prototype Chain:
⢠Every object has __proto__
⢠Functions have prototype
⢠Methods shared via prototype
⢠Memory efficient
javascript
// Constructor function
function Vehicle(type) {
this.type = type;
}
// Add method to prototype
Vehicle.prototype.describe = function() {
return `This is a ${this.type}`;
};
Vehicle.prototype.wheels = 4;
const car = new Vehicle("car");
const bike = new Vehicle("bike");
bike.wheels = 2; // Override for this instance
console.log(car.describe());
console.log(`Car wheels: ${car.wheels}`);
console.log(bike.describe());
console.log(`Bike wheels: ${bike.wheels}`);
// Check prototype chain
console.log(car.hasOwnProperty('type')); // true
console.log(car.hasOwnProperty('describe')); // false (on prototype)You should see
This is a car Car wheels: 4 This is a bike Bike wheels: 2 true false