Created
December 9, 2015 19:58
-
-
Save greyaperez/c5f1c39257880840dc96 to your computer and use it in GitHub Desktop.
Create Singleton Class Instances without Polluting the global scope.
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
/** | |
* 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