In JavaScript, the prototype mechanism provides a way to share properties and methods among all instances of a constructor function or class. This approach helps in managing memory efficiently by avoiding the duplication of methods across multiple instances.
Every JavaScript function has a prototype property, which is an object that is used as a blueprint for instances of that function. When you create an object using a constructor function or a class, it inherits properties and methods from its prototype.
ClassName.prototype.methodName = function() {
// Method definition
};
Memory Efficiency: Instead of each instance having its own copy of a method, all instances share the same method defined in the prototype. This saves memory and improves performance.
Inheritance: JavaScript uses prototypes to implement inheritance. Objects can inherit properties and methods from other objects.
Prototype chaining refers to the process where an object inherits from another object's prototype, which in turn inherits from another prototype, and so on. This chain continues up to the Object.prototype, which is the topmost prototype in JavaScript.
<script>
function Person(name) {
this.name = name;
}
// Adding a method to Person's prototype
Person.prototype.greet = function() {
document.write(`Hello, my name is ${this.name}`);
};
const person1 = new Person('Alice');
person1.greet(); // Output: Hello, my name is Alice
</script>
<script>
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
document.write(`${this.name} makes a noise.`);
};
function Dog(name, breed) {
Animal.call(this, name); // Call the parent constructor
this.breed = breed;
}
// Inherit from Animal's prototype
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
document.write(`${this.name} barks.`);
};
const myDog = new Dog('Rex', 'Labrador');
myDog.speak(); // Output: Rex makes a noise.
myDog.bark(); // Output: Rex barks.
</script>