Anar
Anar

Reputation: 925

JavaScript - What is a singleton class looks like?

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;
     }
}

Upvotes: 0

Views: 119

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

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?

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

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

Upvotes: 1

Related Questions