Singleton Pattern with Javascript
function SingletonClass(name){
//check if instance exist, we can maintain Single instance with this.
if(typeof SingletonClass.instance === 'object'){
return SingletonClass.instance;
}
this.name = name;
SingletonClass.instance = this;
return this;
}
var mySingletonClass = SingletonClass("Variable");
document.write("My SingletonClass name is " + mySingletonClass.name + "<br />")
var nextSingletonClass = SingletonClass("next");
document.write("My SingletonClass name is " + mySingletonClass.name + "<br />")
Another Example
function AppSettings(){
if(typeof AppSettings.instance === 'object'){
return AppSettings.instance;
}
this.name = "Application1";
this.url ="http://www.domain.com";
this.defaultPageSize=30;
this.defaultLang='en';
//.....other application settings
AppSettings.instance = this;
return this;
}
Usage
var v1 = AppSettings.url;
console.log(v1);
Date: 2017-11-13 10:20:00 +0000