views:

1472

answers:

2

I'm using this pattern for singletons, in the example the singleton is PlanetEarth:

var NAMESPACE = function () {

 var privateFunction1 = function () {
  privateFunction2();
 };

 var privateFunction2 = function () {
  alert('I\'m private!');
 };

 var Constructors = {};

 Constructors.PlanetEarth = function () {
  privateFunction1();
  privateFunction2();
 };

 Constructors.PlanetEarth.prototype = {
  someMethod: function () {
   if (console && console.log) {
    console.log('some method');    
   }
  }
 };

 Constructors.Person = function (name, address) {
  this.name = name;
  this.address = address;
 };

 Constructors.Person.prototype = {
  walk: function () {
   alert('STOMP!');
  }
 };

 return {
  Person: Constructors.Person, // there can be many
  PlanetEarth: new Constructors.PlanetEarth() // there can only be one!
 };

}();

Since PlanetEarth's constructor remains private, there can only be one.

Now, something tells me that this self-cooked thing isn't the best one can do, mostly because I don't have an academic education and I tend to solve problems in stupid ways. What would you propose as a better alternative my method, where better is defined as stylistically better and/or more powerful?

Thanks

+1  A: 

http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript

o.k.w
Sorry I'm late, thanks for the direction.
Kaze no Koe
+1  A: 

Why use a constructor and prototyping for a single object?

The above is equivalent to:

var earth= {
    someMethod: function () {
        if (console && console.log)
            console.log('some method');                             
    }
};
privateFunction1();
privateFunction2();

return {
    Person: Constructors.Person,
    PlanetEarth: earth
};
bobince