2

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;
    }
};
Brent Stewart
  • 1,830
  • 14
  • 21
Elaine K
  • 21
  • 1
  • There are no "problems" with it - it works, and there's nothing particularly bad about the pattern - it's mostly a matter of opinion if something else is "better" – codefactor Feb 28 '13 at 01:59
  • Please see this. http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript – Achrome Feb 28 '13 at 02:02
  • Good question but could you fix the typo in your question title (add an "n" at the end)? Could help web searchers in the future. – Matt Browne Feb 28 '13 at 02:06
  • In JS there is a convention of only using variable names that start with capital letters for constructor functions. If you ran code that uses this `Singleton` object through [JSLint](http://jslint.com/) you would get errors. Using the name `Singleton` instead of `singleton` will not effect the functioning of the code but it will make it harder for other programmers to understand your code at a glance. – Useless Code Feb 28 '13 at 06:18

2 Answers2

1

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.

hugomg
  • 68,213
  • 24
  • 160
  • 246
1

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
  };
}());
elclanrs
  • 92,861
  • 21
  • 134
  • 171