In JavaScript, The Prototype is a fundamental concept related to object-oriented programming and inheritance.
Each object in JavaScript has a prototype, which is either null or another object.
The prototype is used for property and method lookup when an object is accessed or modified.
Understanding prototypes is crucial for grasping JavaScript's object-oriented nature.
Objects in JavaScript are linked to a prototype object.
When a property or method is accessed on an object, and the object itself does not have that property or method, JavaScript looks up the prototype chain.
This chain continues until it reaches an object with a null prototype.
This process forms the prototype chain.
Functions in JavaScript have a special property called prototype.
When we create an object using a constructor function, the object's prototype is set to the constructor function's prototype property.
function Car(name, age) { this.name = name; this.year = year; } const car = new Car("Rolls Royce", 2020); console.log(car.__proto__ === Car.prototype); // Outputs: true
While `__proto__` is a non-standard way to access the prototype, the recommended approach is to use `Object.getPrototypeOf()`:
console.log(Object.getPrototypeOf(car) === Car.prototype); // Outputs: true
Methods can be added to the prototype to be shared among all instances created by a constructor function.
Car.prototype.blowHorn = function() { console.log("Pee Pee! Horn Blow by: " + this.name); }; car.blowHorn(); // Outputs: Pee Pee! Horn Blow by: Rolls Royce
This is more memory-efficient than adding methods directly to each instance.
const carPrototype = { petrolEngine: function() { console.log("Petrol."); }, ev: function() { console.log("EV."); }, dual: function() { console.log("EV and Petrol."); } }; const car = Object.create(carPrototype); car.petrolEngine(); // Outputs: Petrol. car.ev(); // Outputs: EV. car.dual(); // Outputs: EV and Petrol.
The "Object.create()" method allows us to create a new object with a specified prototype.