Good Singleton Pattern in JavaScript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I use the following Singleton pattern in JavaScript:

  var exampleClass =(function(){ 
                        //private
                        var a ="test"; 
                        function PrivateMethod()
                        {
                            return a;
                        }
                        //public
                        return{  
                            Test: function() { 
                                   alert(PrivateMethod()); 
                                  } 
                        }
                      })(); 

As I read through StackOverflow I see a lot of other implementations of Singleton and I start to doubt if I couldn t make mine better. I hope someone can tell me what s right or wrong about doing it this way.

Answers

It depends what you want to achieve as the different implementations will have different benefits and limitations.

The simplest implementation is just an object literal:

var singleton = {
    property: "foo",
    method: function() {
        alert( bar );
    }
}

The implementation you mention in the question allows public and private methods by encapsulating the methods in a closure and returning what should be exposed.

Here is an alternative which similarly would allow public and private methods and is more extensible:

function MySingletonClass() {

  if ( arguments.callee._singletonInstance )
    return arguments.callee._singletonInstance;
  arguments.callee._singletonInstance = this;

  this.Foo = function() {
    // ...
  }
}

var a = new MySingletonClass()
var b = MySingletonClass()
Print( a === b ); // prints: true

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/13266086/good-singleton-pattern-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils