Creative Design Patterns in JavaScript: A Brief Tutorial

Here are some models for creating an object: The factory model uses a function to ignore the process of creating specific objects and returning their reference. The prototype model adds the properties of the object to the properties available and shared between all instances. The constructor model defines the properties of the object, while the prototype model defines the methods and shared properties. This is a combination of the manufacturer and prototype models. The object creation model in JavaScript uses the new operator and the name of the function to create a new object.
Mechanisms for creating objects increase flexibility and reuse of existing code. Here in this article we will see the model of creating objects in JavaScript.
Some models to create an object are:
- Factory model
- Builder model
- Prototype model
- Constructor / Prototype boss
Factory model
The factory model uses a function to disregard the process of creating specific objects and returning their reference. It returns a new instance on each call.
Builder model
In the constructor model, instead of returning the function instance, we use the new operator with the name of the function.
function createFruit(name) {
this.name = name;
this.showName = function () {
console.log("I'm " + this.name);
}
}
const fruitOne = new createFruit('Apple');
const fruitTwo = new createFruit('Orange');
fruitOne.showName(); // I'm Apple
fruitTwo.showName(); // I'm orage
Prototype model
The prototype model adds the properties of the object to the properties available and shared between all instances.
function Fruit(name) {
this.name = none;
}
Fruit.prototype.showName = function() {
console.log("I'm " + this.name);
}
const fruitOne = new Fruit('Apple');
fruitOne.showName(); // I'm Apple
const fruitTwo = new Fruit('Orange');
fruitTwo.showName(); // I'm Orange
Constructor / Prototype boss
This is a combination of the manufacturer and prototype models. The constructor model defines the properties of the object, while the prototype model defines the methods and shared properties.
function Fruit() { }
Fruit.prototype.name = name;
Fruit.prototype.showName = function () {
console.log("I'm " + this.name);
}
const fruit = new Fruit();
fruit.name = 'Apple';
fruit.showName(); // I'm Apple
Thanks for reading | Good coding😊
Originally at –https://rahulism.tech/
Key words
Create your free account to unlock your personalized reading experience.