Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Singleton in JavaScript that truly ensures one instance, can be lazy-loaded (you can instantiate it whenever you need it), and has private and public scope.
/* **
*
* Singleton.js - a true Singleton in JavaScript
*
* A Singleton in JavaScript that truly ensures one instance, can be lazy loaded / you
* can instantiate it whenever you need it and has private and public scope.
*
* @author Keith Rosenberg, netPoetica
*
* */
var Singleton = function() {
"use strict";
// If this has has not been instantiated...
if (!Singleton.instance) {
console.log("Singleton.instance is undefined. Creating singleton...");
// Build private members in our private scope. Only the public_members
// object will be able to access them. Note: due to the nuances of
// JavaScript handling of scope, using the 'this' keyword instead of
// 'var' to initialize these members will render them unavailable later.
var _text = 'private';
// Build public members object which will be returned in a closure, providing
// access to the private variables which will no longer be accessible via
// the Singleton object (i.e. cannot use Singleton._text = 'new text')
var public_members = {
text: 'public',
logText: function() {
// Console log the public member variable
console.info("Singleton>>Public Member: " + this.text);
// Console log the private member variable
console.info("Singleton>>Private Member: " + _text);
},
toString: function() {
// Return something more descriptive than [object Object]
return "[object Singleton]";
},
setInstance: function() {
// A workaround for passing a reference to the correct 'this' for
// ensuring that the Singleton class cannot be reinstantiated
Singleton.instance = this;
}
};
// Set the instance as a reference to the public_members object
public_members.setInstance();
return public_members;
}
else {
console.warn("Singleton already has an instance, here it is: " + Singleton.instance);
return Singleton.instance;
}
};
// Creates a new instance of Singleton
var mySingleton = new Singleton();
mySingleton.logText();
// Recieves the existing instance of Singleton
// herSingleton.logText() is a reference to the same function as mySingleton.logText()
var herSingleton = new Singleton();
herSingleton.logText();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.