vendredi 6 janvier 2017

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

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.

Aucun commentaire:

Enregistrer un commentaire