Open In App

Prototype Method – JavaScript Design Pattern

A Prototype Method is a JavaScript design pattern where objects share a common prototype object, which contains shared methods. The prototype method allows you to reuse the properties and methods of the prototype object, and also add new ones as needed. The prototype method is useful for performance optimization, as it avoids creating new functions for each object instance. It also supports prototypal inheritance, which is a different way of implementing object-oriented programming in JavaScript.

Syntax:



function MyObject() {
this.property1 = 'Value 1';
this.property2 = 'Value 2';
}
MyObject.prototype.method1 = function() {
// Method 1 implementation
};
MyObject.prototype.method2 = function() {
// Method 2 implementation
};

Example: In this example, a personPrototype object is created with a greet method, which prints a greeting with the name property. Then, a new object data is created, extending the personPrototype. By setting the name property to ‘Rohan’ and invoking data.greet(), it logs “Hello, my name is Rohan,” demonstrating prototype-based inheritance for shared behavior in JavaScript objects.




// Create a prototype object with a method
const personPrototype = {
    greet() {
        console.log(`Hello, my name is ${this.name}`);
    },
};
 
// Create a new object and extend its prototype
const data = Object.create(personPrototype);
data.name = 'Rohan';
 
// Invoke the method on the extended object
data.greet();

Output

Hello, my name is Rohan


Example: In this example, defines a Car constructor function that creates car objects with properties like model, year, and miles. The toString method is added to each car’s prototype to display car information, and two car instances are logged to the console.




function Car(model, year, miles) {
    this.model = model;
    this.year = year;
    this.miles = miles;
}
Car.prototype.toString = function () {
    return this.model + " has done " + this.miles + " miles";
};
let civic = new Car("Honda Civic", 2009, 20000);
let mondeo = new Car("Ford Mondeo", 2010, 5000);
console.log(civic.toString());
console.log(mondeo.toString());

Output:

Honda Civic has done 20000 miles
Ford Mondeo has done 5000 miles

The prototype method in JavaScript design pattern is one of the core features of the language, and it is widely used in many libraries and frameworks.

Advantages:

Disadvantages:


Article Tags :