Elaine K
Elaine K

Reputation: 21

Are there any problems implementing a Javascript singleton pattern this way?

Does anyone see any problems with the following code block for creating a singleton?

Singleton = {
    getInstance : function() {
        if (Singleton._instance)
            return Singleton._instance;

        Singleton._instance = new function() {
            //create object here
        };

        return Singleton._instance;
    }
};

Upvotes: 2

Views: 99

Answers (2)

elclanrs
elclanrs

Reputation: 94101

Another common singleton pattern is the "Module Pattern", which allows you to declare "private" variables.

var singleton = (function singletonMod() {
  // private
  var foo = 'foo';

  function getFoo() {
    return foo;
  }

  // expose public vars and methods
  return {
    getFoo: getFoo
  };
}());

Upvotes: 1

hugomg
hugomg

Reputation: 69944

In Javascript its usually simpler to just create the singleton object using an object literal and put it in a variable somewhere where people can get it.

var mySingleton = {
    some_variable: 10,
    some_method: function(x){
        console.log(this.some_variable * x);
    }
}

mySingleton.some_method();

Using a complicated pattern instead is probably overkill.

Upvotes: 1

Related Questions