SingleTon classes in Javascript

Following is an example of singleton/private classes in JavaScript.



var singleTonClass = function(){ //constructor...

	//instance is private class...
	var instance = function(){
		this.count = 0;
		this.Name = "this-" + Math.random();
		this.AddCount = function(){
			this.count += 1;
		}
	}

	//this will return the instance of private class...
	if(singleTonClass.classInstance == null || singleTonClass.classInstance === undefined){
		singleTonClass.classInstance = new instance();
	}
	return singleTonClass.classInstance;
};
//this should not be part of the singleTonClass...as this should be created once...
//prototype will make sure that we only have one instance of classInstance...
singleTonClass.prototype.classInstance = null;



var instance = new singleTonClass();
var instance1 = new singleTonClass();
var instance2 = new singleTonClass();
var instance3 = new singleTonClass();
var instance4 = new singleTonClass();


console.log(instance.Name);
console.log(instance.count);
instance.AddCount();
console.log(instance1.Name);
console.log(instance1.count);
instance1.AddCount();
console.log(instance2.Name);
console.log(instance2.count);
instance2.AddCount();
console.log(instance3.Name);
console.log(instance3.count);
instance3.AddCount();
console.log(instance4.Name);
console.log(instance4.count);


Name property for all variable should always return same string value and count should increase for all objects if we increase for one object.
Add Comments :

Login

Register