This article is a part of Series: Design Patterns in JavaScript,
The prototype pattern falls under a creational design pattern category, as described by the GoF Prototype design pattern, used to create an object from the template, where the template is also an object. This pattern is based on the prototypical inheritance in which we create an object which acts as a prototype for the other object. Uses: In JavaScript sometimes, we require an object initialization with the default properties or functions. In other words, we require an inheritance for newly created objects which is based on a template (previously created object).
We use prototypical inheritance in JavaScript (which is a native behavior of JavaScript) to achieve the same. Using Code: Let’s simulate a simple folder class, using function in JavaScript. -
- function Folder() {}
-
- Folder.prototype =
- {
- constructor: Folder,
- name: "New Folder",
- createOn: new Date().toString(),
- getInfo: function() {
- console.log("Name: " + this.name + "\nCreate On: " + this.createOn);
- }
- };
-
- var myFolder = Object.create(Folder.prototype);
- console.log(myFolder.name);
- console.log(myFolder.getInfo());
We used Object.create function to create a prototype here. myFolder is a prototype which can be used further in the Application. We can create as many as prototypes as per the requirement. In order to change the default property, we can simply the change name, using: - myFolder.name = "My Folder";
- console.log(myFolder.name);
In some cases, we need to add more properties and functions in the prototype object. We can also add the new properties, using Object.create function as follows: - var myFolder = Object.create(Folder.prototype,
- {
- id: {
- value: "temp id"
- }
- });
- console.log(myFolder.id);
- but
- if you want change id as: myFolder.id = "new id";
You will be surprised that ID is still having an old value in it. The reason is that Object.create uses Object.defineProperties to create the properties. Let’s look into the code, given above, in detail. - var myFolder = Object.create(Folder.prototype,
- {
- id: {
- value: "temp id"
- enumerable: false,
- writable: false,
- configurable: false
- }
- });
Thus, when we added ID, we just set the value property. If we want to modify the value for the defined property, we need to make it writable. Let’s change it as follows: - var myFolder = Object.create(Folder.prototype,
- {
- id: {
- value: "temp id",
- writable: true
- }
- });
Now if you change ID, you will get the expected result: - myFolder.id="new id";
- console.log(myFolder.id);
Conclusion: In this article, I explained how we can use the prototype design pattern in JavaScript. I hope you have enjoyed it.