HomeToolsAbout

Singleton

Singleton using closure and IIFE

// singleton definition creation const Singleton = (function () { let instance; function createInstance() { // returns an object or value that will hold Singleton data return { data: "I am the singleton instance" }; } // creating method to get the instance via closure return { getInstance: function () { // runs when instance does not exist if (!instance) { instance = createInstance(); } // returns the same instance when singleton exists return instance; } }; })(); // immediately invoking function here // usage const instance1 = Singleton.getInstance(); const instance2 = Singleton.getInstance(); console.log(instance1 === instance2); // true

Using Class

class Singleton { // Static property to hold the singleton instance static instance = null; constructor() { // handling multiple instantiation if (Singleton.instance) { return Singleton.instance; } // object itself as a singleton Singleton.instance = this; // some data to store or reference this.data = "Singleton instance data"; } } const singleton1 = new Singleton(); const singleton2 = new Singleton(); console.log(singleton1 === singleton2); // true

Exporting to another file

// singleton.js class Singleton { constructor() { if (Singleton.instance) { return Singleton.instance; } Singleton.instance = this; this.data = "Module Singleton Data"; } } export default new Singleton(); // Usage in another file import Singleton from './singleton.js'; const singleton1 = Singleton; const singleton2 = Singleton; console.log(singleton1 === singleton2); // true
AboutContact