In JavaScript, prototype and prototype inheritance are key concepts related to how objects inherit properties and methods from other objects.
Prototype:
- Each JavaScript object has a prototype. The prototype is a reference to another object. Objects in JavaScript are linked to a prototype object, and they inherit properties and methods from that prototype.
-
When you access a property or method on an object, JavaScript first checks if that property or method exists on the object itself. If not found, it looks up the prototype chain until it finds the property or method or reaches the end of the chain (the prototype of
Object
).
Prototype Inheritance:
- In JavaScript, objects can inherit properties and methods from other objects through prototype inheritance. This means an object can have a prototype object, and it inherits properties and methods from that prototype.
-
When you create an object using a constructor function or the
class
syntax, the object's prototype is set to the constructor function'sprototype
property.
Example using constructor functions:
function Animal(name) {
this.name = name;
}
// Adding a method to the prototype of Animal
Animal.prototype.walk = function() {
console.log(this.name + ' is walking.');
};
// Creating objects using the Animal constructor
let dog = new Animal('Buddy');
let cat = new Animal('Whiskers');
// Objects inherit the walk method from Animal's prototype
dog.walk(); // Output: "Buddy is walking."
cat.walk(); // Output: "Whiskers is walking."
In the example above:
-
Animal is a constructor function, and
walk
is added toAnimal.prototype
. -
Objects created with
new Animal
() (likedog and cat
) inherit the walk method from Animal.prototype.
This inheritance chain continues up to the built-in Object.prototype
, which serves as the final link in the prototype chain.
Understanding prototypes and prototype inheritance is fundamental to JavaScript's object-oriented nature. It allows for more efficient memory usage by sharing common properties and methods among objects and enables a flexible way to add functionality to objects.