Skip to content

Instantly share code, notes, and snippets.

@greyaperez
Created December 9, 2015 19:58
Show Gist options
  • Save greyaperez/c5f1c39257880840dc96 to your computer and use it in GitHub Desktop.
Save greyaperez/c5f1c39257880840dc96 to your computer and use it in GitHub Desktop.
Create Singleton Class Instances without Polluting the global scope.
/**
* Adds a {@code getInstance} static method that always return the same instance
* object.
* @param {!Function} ctor The constructor for the class to add the static
* method to.
*/
function addSingletonGetter(ctor) {
ctor.getInstance = function() {
if (ctor.instance_) {
return ctor.instance_;
}
return ctor.instance_ = new ctor;
};
}
var project = { some: { namespace: { } } };
project.some.namespace.StateManager = function() {
this.x_ = 5;
};
project.some.namespace.prototype.getX = function() { return x; }
addSingletonGetter(project.some.namespace.StateManager);
// Now to reference it anywhere...
project.some.namespace.StateManager.getInstance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment