Prototype Pattern Overview
According to The GOF, the prototype pattern creates objects based on a template of an existing object through cloning.
We can think of the prototype pattern as being based on prototypal inheritance where we create objects which act as prototypes for other objects. The prototype object itself is effectively used as a blueprint for each object the constructor creates.
One of the benefits of using the prototype pattern is that we're working with the prototypal strengths JavaScript has to offer natively rather than attempting to imitate features of other languages. With other design patterns, this isn't always the case.
To demonstrate this prototype pattern, we use Object.create() method which creates an object which has a specified prototype and optionally contains specified properties as well (e.g Object.create( prototype, optionalDescriptorObjects )).
For example, the below diagram shows a prototype of different cars:
For example, the below diagram shows a prototype of different cars:
Prototype Pattern Example
In this example, we have an Employee object that we use as the prototype to create another object employee1 with JavaScript’s Object.create feature:
// using Object.create Method
var Employee = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29,
getFullName : function (){
return user.firstName + " " + user.lastName;
}
}
var employee1 = Object.create(Employee);
// access new object properties
console.log('firstName :', employee1.firstName);
console.log('lastName :', employee1.lastName);
console.log('emailId :', employee1.emailId);
console.log('age :', employee1.age);
Output:
firstName : Ramesh
lastName : Fadatare
emailId : ramesh@gmail.com
age : 29
Object.create() method has two parameters. A first parameter is a mandatory object that serves as the prototype of the new object to be created and this we have demonstrated in the above example. A second parameter is an optional object which contains the properties to be added to the new object. For example, we are adding emailId and age properties to the new object here:
// using Object.create Method
var Employee = {
firstName : 'Ramesh',
lastName : 'Fadatare',
getFullName : function (){
return user.firstName + " " + user.lastName;
}
}
var employee1 = Object.create(Employee,{
"emailId": {
value: "ramesh@gmail.com",
// writable:false, configurable:false by default
enumerable: true
},
"age": {
value: 29,
enumerable: true
}
});
// access new object properties
console.log('firstName :', employee1.firstName);
console.log('lastName :', employee1.lastName);
console.log('emailId :', employee1.emailId);
console.log('age :', employee1.age);
Output:
firstName : Ramesh
lastName : Fadatare
emailId : ramesh@gmail.com
age : 29
Related JavaScript Design Patterns
- JavaScript Factory Pattern with Example //Popular
- JavaScript Builder Pattern Example //Popular
Comments
Post a Comment
Leave Comment