Singleton Design Pattern JavaScript

Home >> Blog >> Singleton Design Pattern JavaScript
By Admin Sep 04, 2020

JavaScript: Singleton Design Pattern with Real Time Example
Singleton Design Pattern:

It is Creational Patterns which focus on how to instantiate an object.

Singleton Design Pattern ensure that a class has only one instance, and provides a way to access it globally.

In other words, Singletons are used to create an instance of a class if it does not exist or else return the reference of the existing one.

You may also like Node.js Interview Questions
Singleton Design Pattern using IIFE
var Singleton = (function() { var instance; function createInstance() { var object = new Object("I am the instance"); return object; } return { getInstance: function() { if (!instance) { instance = createInstance(); } return instance; } }; })(); function myFunc() { var instance1 = Singleton.getInstance(); var instance2 = Singleton.getInstance(); console.log(instance1 === instance2); }
You may also like React.js Interview Questions
Singleton Design Pattern using ES6
class Singleton { static instance; constructor() { if (instance) { return instance; } this.state = "Singleton ES6"; this.instance = this; } } export default Singleton; let instance1 = new Singleton(); let instance2 = new Singleton(); console.log(instance1 === instance2); //output: true