Created
January 19, 2010 18:55
-
-
Save thisivan/281166 to your computer and use it in GitHub Desktop.
Creating Singleton objects with JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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