paint-brush
Creational Design Patterns In JavaScript: A Brief Tutorialby@rahull
1,176 reads
1,176 reads

Creational Design Patterns In JavaScript: A Brief Tutorial

by RahulApril 6th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Some patterns to create an object are: The factory pattern uses a function to abstract away the process of creating specific objects and returning their reference. The prototype pattern adds the properties of the object to the properties that are available and shared among all instances. The constructor pattern defines object properties, while the prototype pattern defines methods and shared properties. This is a combination of the constructor and prototype patterns. The Object Creation Pattern in JavaScript uses the new operator along with the function name to create a new object.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Creational Design Patterns In JavaScript: A Brief Tutorial
Rahul HackerNoon profile picture

Object creation mechanisms increase the flexibility and reuse of existing code. Here in this post, we will see the Object Creation Pattern in JavaScript.

Some patterns to create an object are:

  • Factory pattern
  • Constructor pattern
  • Prototype pattern
  • Constructor / Prototype pattern

Factory Pattern

The factory pattern uses a function to abstract away the process of creating specific objects and returning their reference. It returns a new instance whenever called.

Constructor Pattern

In the constructor pattern, instead of returning the instance from the function, we use the new operator along with the function name.

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 Pattern

The prototype pattern adds the properties of the object to the properties that are available and shared among 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 pattern

This is a combination of the constructor and prototype patterns. The constructor pattern defines object properties, while the prototype pattern defines 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 | Happy Coding😊

Originally at — https://rahulism.tech/