Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest/cleanest way to implement a singleton in JavaScript

What is the simplest/cleanest way to implement the singleton pattern in JavaScript?

like image 704
Jakub Arnold Avatar asked Sep 25 '09 20:09

Jakub Arnold


People also ask

What is the best way to implement a singleton class?

Eager initialization: In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a Singleton class. By making the constructor as private you are not allowing other class to create a new instance of the class you want to create the Singleton.


2 Answers

I think the easiest way is to declare a simple object literal:

var myInstance = {   method1: function () {     // ...   },   method2: function () {     // ...   } }; 

If you want private members on your singleton instance, you can do something like this:

var myInstance = (function() {   var privateVar = '';    function privateMethod () {     // ...   }    return { // public interface     publicMethod1: function () {       // All private members are accessible here     },     publicMethod2: function () {     }   }; })(); 

This has been called the module pattern, and it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.

If you want to prevent the modification of the singleton object, you can freeze it, using the ES5 Object.freeze method.

That will make the object immutable, preventing any modification to the its structure and values.

If you are using ES6, you can represent a singleton using ES Modules very easily, and you can even hold private state by declaring variables at the module scope:

// my-singleton.js const somePrivateState = []  function privateFn () {   // ... }  export default {   method1() {     // ...   },   method2() {     // ...   } } 

Then you can simply import the singleton object to use it:

import myInstance from './my-singleton.js' // ... 
like image 92
Christian C. Salvadó Avatar answered Oct 22 '22 18:10

Christian C. Salvadó


I think the cleanest approach is something like:

var SingletonFactory = (function(){     function SingletonClass() {         //do stuff     }     var instance;     return {         getInstance: function(){             if (instance == null) {                 instance = new SingletonClass();                 // Hide the constructor so the returned object can't be new'd...                 instance.constructor = null;             }             return instance;         }    }; })(); 

Afterwards, you can invoke the function as

var test = SingletonFactory.getInstance(); 
like image 32
sebarmeli Avatar answered Oct 22 '22 16:10

sebarmeli