Prototypes let JavaScript objects share features like methods and properties without copying them. This saves memory and helps organize code.
0
0
Why prototypes are needed in Javascript
Introduction
When many objects need the same behavior, like all cars having a drive method.
When you want to add new features to existing objects without changing each one.
When you want to save memory by sharing methods instead of duplicating them.
When you want to create a chain of objects that can share and override features.
Syntax
Javascript
function Constructor() { this.property = 'value'; } Constructor.prototype.method = function() { // shared method code };
The prototype is an object that holds shared methods and properties.
Objects created with new Constructor() can use methods from Constructor.prototype.
Examples
This example shows a
Person constructor with a shared greet method on its prototype.Javascript
function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, my name is ${this.name}`; }; const alice = new Person('Alice'); console.log(alice.greet());
Both
car1 and car2 share the same drive method from Car.prototype.Javascript
function Car(model) { this.model = model; } Car.prototype.drive = function() { return `${this.model} is driving`; }; const car1 = new Car('Toyota'); const car2 = new Car('Honda'); console.log(car1.drive()); console.log(car2.drive());
Sample Program
This program creates an Animal constructor. The speak method is shared by all animals through the prototype. Both dog and cat use the same method without duplicating it.
Javascript
function Animal(name) { this.name = name; } Animal.prototype.speak = function() { return `${this.name} makes a noise.`; }; const dog = new Animal('Dog'); const cat = new Animal('Cat'); console.log(dog.speak()); console.log(cat.speak());
OutputSuccess
Important Notes
Prototypes help keep your code efficient by sharing methods.
You can add or change prototype methods anytime, and all objects using it will see the change.
Understanding prototypes is key to mastering JavaScript's object system.
Summary
Prototypes let objects share methods and properties to save memory.
They allow adding features to many objects easily.
Using prototypes helps organize and reuse code in JavaScript.