If you know the Singleton Pattern from Java, then this is what you need, to implement a Singleton in JavaScript:
singleton.js
var Singleton = (function(){
var instance = null;
function PrivateConstructor(){
var number = Math.round(Math.random() * 100);
var text = 'Change me.';
this.setNumber = function(numberValue){
number = numberValue;
}
this.getNumber = function(){
return number;
}
this.setText = function(textValue){
text = textValue;
}
this.getText = function(){
return text;
}
this.saySomething = function(){
alert(text);
}
}
return new function(){
this.getInstance = function(){
if (instance == null){
instance = new PrivateConstructor();
instance.constructor = null;
}
return instance;
}
}
})(); |
var Singleton = (function(){
var instance = null;
function PrivateConstructor(){
var number = Math.round(Math.random() * 100);
var text = 'Change me.';
this.setNumber = function(numberValue){
number = numberValue;
}
this.getNumber = function(){
return number;
}
this.setText = function(textValue){
text = textValue;
}
this.getText = function(){
return text;
}
this.saySomething = function(){
alert(text);
}
}
return new function(){
this.getInstance = function(){
if (instance == null){
instance = new PrivateConstructor();
instance.constructor = null;
}
return instance;
}
}
})();
How to use it:
<script src="./js/singleton.js"></script>
<script>
var firstInstance = Singleton.getInstance();
var secondInstance = Singleton.getInstance();
if(firstInstance === secondInstance){
document.write('We have two instances.<br/>');
}
document.write(firstInstance.getNumber());
document.write('<br/>');
document.write(secondInstance.getNumber());
firstInstance.setText('Hello World.');
secondInstance.saySomething(); // displays 'Hello World.'
</script> |
<script src="./js/singleton.js"></script>
<script>
var firstInstance = Singleton.getInstance();
var secondInstance = Singleton.getInstance();
if(firstInstance === secondInstance){
document.write('We have two instances.<br/>');
}
document.write(firstInstance.getNumber());
document.write('<br/>');
document.write(secondInstance.getNumber());
firstInstance.setText('Hello World.');
secondInstance.saySomething(); // displays 'Hello World.'
</script>
Without constructor:/h2>
var Singleton = (function() {
// Private
var text = "Hello World!";
// Public
return {
setText: function(value) {
text = value;
},
getText: function() {
return text;
}
};
})();
alert(Singleton.getText()); |
var Singleton = (function() {
// Private
var text = "Hello World!";
// Public
return {
setText: function(value) {
text = value;
},
getText: function() {
return text;
}
};
})();
alert(Singleton.getText());