Skip to content

Instantly share code, notes, and snippets.

@poksme
Created March 28, 2013 12:09
Show Gist options
  • Save poksme/5262659 to your computer and use it in GitHub Desktop.
Save poksme/5262659 to your computer and use it in GitHub Desktop.
How to make a singleton in javascript
function MySingletonObject() {
// SINGLETON CONSTRUCTOR
if (MySingletonObject.prototype._singletonInstance) {
return MySingletonObject.prototype._singletonInstance;
}
MySingletonObject.prototype._singletonInstance = this;
//
// OBJECT PROPERTIES
this.PublicProperty = 42;
var PrivateProperty = "foo";
//
// OBJECT METHODS
this.PublicMethod = function () {
return true;
}
var PrivateMethod = function () {
return "bar"
}
//
}
// USAGE
var mso = new MySingletonObject();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment