How to write a singleton class in javascript

If I look at my stats, a lot of people are wondering how to write a singleton class. I already wrote about it before but my old solution exposed the instance of the class so more than one instance could be created thus making it not completly a singleton class.

Here’s the new solution using a private variable for the instance.

  1. function Cats() {
  2.   var names = [];
  3.  
  4.   this.singletonInstance = null;
  5.  
  6.   // Get the instance of the Cats class
  7.   // If there’s none, instanciate one
  8.   var getInstance = function() {
  9.     if (!this.singletonInstance) {
  10.       this.singletonInstance = createInstance();
  11.     }
  12.     return this.singletonInstance;
  13.   }
  14.  
  15.   // Create an instance of the Cats class
  16.   var createInstance = function() {
  17.     // Here, you return all public methods and variables
  18.     return {
  19.       add : function(name) {
  20.         names.push(name);
  21.         return this.names();
  22.       },
  23.       names : function() {
  24.         return names;
  25.       }
  26.     }
  27.   }
  28.  
  29.   return getInstance();
  30. }

How to use it

  1. function run() {
  2.   // Add a new cat
  3.   var cat1 = new Cats();
  4.   cat1.add("Mistigri");
  5.   jsKataEx.assert(cat1.names().length == 1, "cat1 contains 1 cat : " + cat1.names().toString());
  6.    
  7.   // Use another instance
  8.   var cat2 = new Cats();
  9.   jsKataEx.assert(cat2.names().length == 1, "cat2 contains Mistigri added in cat1 : " + cat2.names().toString());
  10.    
  11.   // Add another cat in the other instance
  12.   cat2.add("Felix");
  13.   jsKataEx.assert(cat2.names().length == 2, "cat2 contains Mistigri and Felix" + cat2.names().toString());
  14.   jsKataEx.assert(cat2.names().length == 2, "cat1 also contains Mistigri and Felix" + cat1.names().toString());
  15. }

Get the code on GitHub and see it live in action.

Comments

  1. # JavaScript Countdown Timer September 30, 2009 at 22:20:09

    very cool & good tip, thank you very much for sharing.

    Can I share this snippet on my JavaScript library?

    Awaiting your response. Thank

  2. [...] How to make a singleton in javascript April 4, 2007 by Dan Simard black belt, object-oriented | 23 comments [UPDATE : This post is outdated. Check out the new post on singletons.] [...]

  3. # trice22 October 5, 2009 at 06:12:19

    Could you explain how this is supposed to be used?

    This doesn’t do much:

    var foo = new Cats();
    var bar = new Cats();

    foo.add(”Joe”);
    bar.add(”Bert”);

    foo.names() // => ["Joe"]

    Cheers.

  4. # KooiInc November 23, 2009 at 12:02:42

    You could rewrite this (for more efficiency):

    function Cats(){
    var names = [],
    proto = arguments.callee.prototype;
    if (!proto._initiated){
    proto.add = function(name) {
    names.push(name);
    return this.names();
    };
    proto.names = function() {
    return names;
    };
    proto._initiated = true;
    }
    return this;
    }

Post a comment

Comments are moderated and innapropriate ones won't be approved. Please respect this public space.