How to write a singleton class in javascript using IIFE module pattern?

465 views Asked by At

How to write a singleton class in javascript using IIFE module pattern ? Can you plz provide an example?

I tried something like this, but it fails for x2.getInstance. As per my understanding, x2.getInstance() should get the same instance as x1.getInstance(). How can I achieve this using IIFE module pattern ??

var x = (function(){

    var instance ;
    var vconstructor = function(){};
    //vconstructor.prototype.method1 = function(){}
    //vconstructor.prototype.method2 = function(){}
    vconstructor.prototype.getInstance = function(){
        if (!instance) {
          console.log('critical section');
          instance = somefunc();
          return instance;
    }
    };  

    function somefunc(){
        return { "key1": "value1"};
    }

    return vconstructor;
})();

var x1 = new x();
console.log('1.');
console.log(x1 instanceof x);
console.log(x1);
console.log('2.' + x1.getInstance());  
var x2 = new x();
console.log(x2);
console.log('x2: ' + x2.getInstance());   

Kindly advise.

1

There are 1 answers

4
Sahadev On

You can try this:

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 run() {

    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();

    alert("Same instance? " + (instance1 === instance2));  
}