Tuesday 8 December 2009

JavaScript – Create Singleton… No… Static Class

The following class is a normal javascript class:

function Calculator() {

// public functions
this.Add = add;
this.Subtract = subtract;

// private functions
function add(a, b)
{ return a + b; }

function subtract(a, b)
{ return a - b; }

// private variable
var name = "pooya";

// public variable
this.Name = name;

};

And this is how you use it:

var calculatorObject = new Calculator();
calculatorObject.Add(1, 2);

The following class is a static version of the same class:

var Calculator = (function() {

// private variable
var name = "pooya";

// private static functions
function add(a, b)
{ return a + b; }

// all the public members should be added to return (comma separated)
return {
// public function using delegate
Add: add
,
// public function embedding the implementation
Subtract: function(a, b)
{ return a - b; }
,
// public variable
Name: name
}
})();

Now you can simply use the following:

Calculator.Add(1, 2);

Notes:

I have seen many people saying this is how you create a Singleton class which is incorrect.

Please note that in the second Calculator class, no instance member can be defined which means "this" doesn't work, the following is invalid: "this.Name = name"

All members are considered static because of the way it has been defined.

The difference is that in Singleton class you can define instance members, however, in static class like this one you can’t.

You can argue that Singleton in C# is different from Singleton in JavaScript but in my view Singleton is Singleton no matter what language, so this is how you define a static class in JavaScript.

No comments: