Skip to content

Instantly share code, notes, and snippets.

@thisivan
Created January 19, 2010 18:55
Show Gist options
  • Save thisivan/281166 to your computer and use it in GitHub Desktop.
Save thisivan/281166 to your computer and use it in GitHub Desktop.
Creating Singleton objects with JavaScript
// Defining constructor function
function SingletonObject() {
// TODO: Add your own initialization code here
this._message = 'Hello Prototype World!';
};
// Current instance property
SingletonObject._instance = null;
SingletonObject.getInstance = function() {
if (SingletonObject._instance === null) {
SingletonObject._instance = new SingletonObject();
}
return SingletonObject._instance;
}
// Defining instance functions
SingletonObject.prototype.sayHello = function(message) {
alert(this.message);
};
SingletonObject.prototype.setMessage = function(message) {
this.message = message;
};
// Set message to a singleton object
SingletonObject.getInstance().setMessage('Singleton Message');
// Say hello twice from the same instance:
SingletonObject.getInstance().sayHello();
SingletonObject.getInstance().sayHello();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment