In the previous post, we discussed the benefits of module patterns, why they can be helpful and when can it create problems.
Prototype design pattern
While discussing module patterns, we came across memory issues that we face when creating duplicate functions. The prototype pattern is also about duplicating objects while keeping performance in mind. It is considered one of the best ways to create an object. The objects created are shallow clones of the original object that are passed around.
The prototype object holds the default values from the original object to newly created objects. JavaScript being a prototypal language, we use this pattern for constructing new objects and their prototypes. So it is very powerful when working with objects that should have access to the same properties. To clone an object, a constructor must be initiated first. Then we can bind variables and methods to objects using the prototype
keyword. Let’s have a look at a basic example:
var Tata = function() {
this.numWheels = 4;
this.manufacturer = 'Tata';
this.make = 'Nexon';
}
Tata.prototype.go = function() {
// Rotate wheels
}
Tata.prototype.stop = function() {
// Apply brake pads
}
We can provide encapsulation of public and private variables/methods similar to module pattern. We can do it by changing above to following:
var Tata = function() {
this.numWheels = 4;
this.manufacturer = 'Tata';
this.make = 'Nexon';
}
Tata.prototype = function() {
var go = function() {
// Rotate wheels
};
var stop = function() {
// Apply brake pads
};
return {
onPressBrakePedal: stop,
onPressGasPedal: go
}
}();
In the above example, we shielded methods go
and stop
from returning objects due to being outside of returned object’s scope.
Summing up pros and cons:
Pros
- Prototypes are native to JavaScript
- Functions are loaded in memory once only
- Allows extending an existing object, using prototypal inheritance, which is a built-in language
Cons
- Client application will be unaware of object creation and representation
It requires both constructor and function prototype.
The constructor will be going to contain all variables. For each instance that will be created, we’ll have a new set of variables to work with. So it can be a benefit actually.
Next, we’ll be understanding the Observer pattern. Stay tuned for the next post in this series.