Prototype Pattern in JavaScript
Prototype patterns are needed when the object that you need to create is time-consuming, requires intensive resources, and is expensive.
Join the DZone community and get the full member experience.
Join For FreeAs a sound JavaScript developer, you must write clean, easy-to-understand, and maintain code. You solve exciting and unique problems that might not require unique solutions. You may have written code that resembles the solution to a complex problem you encountered before. Although you may not acknowledge it, you were using Design patterns.
Design patterns refer to a general reusable and repeatable solution for a common set of problems while developing a software solution. Design patterns are not a finished project to be transformed directly into the source code. However, it is a template that helps developers understand the way to solve different problems with different solutions in multiple scenarios.
Using design patterns while coding can help you speed up the development process as it provides proven paradigms for development. In the broad context, there are three types of design patterns:
- Creational Design Pattern: It includes class and object creational patterns, namely abstract factory, builder, factory method, object pool, prototype, and singleton.
- Structural Design Pattern: This design pattern is all about the object and class composition and is further divided into the adapter, bridge, composite, decorator, facade, proxy, flyweight, and private class data patterns.
- Behavioral Design Pattern: It is the design pattern that’s focused on object communication. Behavioral design pattern consists of different patterns such as command, chain of responsibility, interpreter, iterator, memento, mediator, observer, null object, state, template method, strategy, and visitor.
But in today’s blog, we will cover the prototype design pattern in JavaScript. So, let’s get started!
The Prototype Pattern
Prototypes are object-based creational design patterns. Prototype pattern focuses on creating objects that can be used as a blueprint for any object that constructors create. It allows developers to hide the complexity to create new instances from the client. In the prototype pattern, the existing object is copied instead of creating it from the ground up. The existing object acts as a blueprint and includes the state of an object. It also allows newly copied objects to change their state if required, saving costs and development time.
Prototype patterns are needed when the object you create is time-consuming, requires intensive resources, and is expensive. The best and simple way to copy an object from an existing one is through the clone() method and a constructor function.
Prototype Pattern in JavaScript
Now that we have an overview of the prototype design pattern let’s take a look at what it looks like in JavaScript and how we can implement it in our code.
As we have understood, the core aim of a prototype pattern is to create objects that can be used as the blueprint or template for any object a constructor creates. To achieve this, prototype design patterns use prototypal inheritance. Moreover, with the native support for the prototypal inheritance, which can be accessed by objects using a prototype chain in JavaScript, it becomes easier to work with prototype patterns.
For example, we can create a prototype method Car to create different types of car objects while returning their reference in turn as follows:
//Prototype function syntax
// The Constructor (Part 1)
// An object must be defined with parameters
function Car(name) {
this.name = name;
}
// Function Prototype (Part 2)
// Add functionality and extend objects
Car.prototype.showCarName = function () {
//console.log('This is ' + this.name);
return 'This is ' + this.name;
}
// Calling Prototype based code
// Resembles traditional OOP styles
const carOne = new Car('SUV');
const carTwo = new Car('Sedan');
var car1 = carOne.showCarName();
var car2 = carTwo.showCarName()
console.log("Using Prototype pattern method - carOne: ", carOne) //returns objects own defined properties and methods
console.log("Using Prototype pattern method - carOne function length: ", Object.getOwnPropertyNames(carOne).length)
console.log("carOne Using Prototype pattern method type? : ", typeof carOne);// object
console.log("Using Prototype pattern method - carTwo: ", carTwo) //returns objects own defined properties and methods
console.log("Using Prototype pattern method - carTwo function length: ", Object.getOwnPropertyNames(carTwo).length)
console.log("carOne Using Prototype pattern method type? : ", typeof carTwo);// object
console.log("Using Prototype pattern - Object creation of carOne: " + car1);
console.log("Using Prototype pattern - Object creation of carTwo: " + car2);
Apart from returning the references from the Car prototype method, we have also created two different objects named carOne and carTwo that will call the prototype pattern constructor Car. When we pass names to these objects like SUV and Sedan, respectively, it will return new Car instances whenever called by the Car constructor using the prototype.
Advantages and Disadvantages of JavaScript Prototype Pattern
Advantages of JavaScript Prototype Pattern are as follows:
- Add or Remove Products at Run-time: Using the prototypical instance in the prototype pattern, you can implement concrete classes into the system. It makes the system more flexible for clients as they can add or remove prototype objects at run-time.
- Reusability: A prototype pattern can be used when creating instances of a complex class with many default values, allowing developers to focus on other activities.
- Simple New Object Creation: In the prototype pattern, you can create objects simply by calling the clone() method, which is easy to read and also hides the complexity of object creation.
- Specifying New Objects by varying value & structure: Using object composition in a prototype pattern system, you can define new behavior for an object variable without defining new classes. Besides, in the prototype pattern, objects are built from parts and subparts, allowing you to instantiate complex structures for better reusability.
- Minimizes Sub Classes: The prototype pattern enables you to clone a prototype object rather than asking the factory method to create a new one. It reduces the class hierarchy and complexity of the system.
Remembering the advantages of the prototype pattern in JavaScript, let’s take a look at its disadvantages as well:
- Developers cannot see concrete classes in prototype models.
- It is costly and also makes calculating the number of iterations needed certain.
- It becomes a must to incorporate clone () or other copy methods to each subclass.
- Sometimes, cloning the existing classes or objects becomes complex. For instance, a cloneable interface constrains all classes/implementations to incorporate the clone() method (even when some classes may not need it).
- Implementing the clone() method can create complications when the subclass consists of objects that do not support copying.
Before you get started with using prototype models in your system, make sure that you only use the prototype pattern while creating a web application system that should be independent of how its products are built, composed, and represented. Another scenario when you can use a prototype pattern is when the instantiated classes are specified at run-time.
Other key points that you need to remember are:
- Three categories of design patterns can be distinguished as creational, structural, and behavioral.
- Design patterns are blueprints or templates that help developers solve common problem sets.
- Prototype pattern is an object-creational design pattern.
- Prototype pattern focuses on creating objects that can be used as a blueprint for any object that constructors create.
- Prototype design patterns use prototypal inheritance.
So that was all about the prototype pattern, but that’s not the end, and we will be sharing more posts on different design patterns for JavaScript soon. We hope you find this article interesting and helpful for your future projects.
Opinions expressed by DZone contributors are their own.
Comments