0

I have 2 Obj: I want to know that if they are Singleton?

a.

var OBJ = function () {
}

OBJ.prototype = {
    setName : function (name) {
        this.name = name;
    },
    getName : function () {
        return this.name;
    }
}

b.

var OBJ = {
     setName : function (name) {
         this.name = name;
     },
     getName : function () {
        return this.name;
     }
}
kinakuta
  • 9,029
  • 1
  • 39
  • 48
Anar
  • 925
  • 2
  • 8
  • 15
  • Can you format your question properly? I'm not going to keep editing it. – Blender Feb 26 '13 at 07:13
  • @Blender I don't know I can not make the second block in code. I don't know why I can not see the tool bar and preview it. – Anar Feb 26 '13 at 07:15
  • This will be helpful: http://www.hardcode.nl/subcategory_1/article_526-singleton-examples-in-javascript.htm – cclerv Feb 26 '13 at 07:20
  • @cclerville thank you for your helping, so the second one should be a singleton, but what about the first one? – Anar Feb 26 '13 at 07:26

2 Answers2

1

You can check it by creating two instances of class and compare them:

 Print( a === b ); // prints: true

if prints true class is singleton

Or you can try this code for SingletonPattern:

function MyClass() {

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

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

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

Best Solution For Singleton Pattern

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

This will help you How to write a singleton class in javascript

 function Cats() {
    var names = [];

    // Get the instance of the Cats class
    // If there's none, instanciate one
    var getInstance = function() {
        if (!Cats.singletonInstance) {
            Cats.singletonInstance = createInstance();
        }
        return Cats.singletonInstance;
    }
    // Create an instance of the Cats class
    var createInstance = function() {
        // Here, you return all public methods and variables
        return {
            add : function(name) {
                names.push(name);
                return this.names();
            },
            names : function() {
                return names;
            }
        }
    }
    return getInstance();
}

More on http://www.javascriptkata.com/2009/09/30/how-to-write-a-singleton-class-in-javascript/

Also it can be possible duplicate of Javascript: best Singleton pattern and Simplest/Cleanest way to implement singleton in JavaScript?

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106