Skip to content

Instantly share code, notes, and snippets.

@benbabics
Created March 6, 2013 21:12
Show Gist options
  • Save benbabics/5103135 to your computer and use it in GitHub Desktop.
Save benbabics/5103135 to your computer and use it in GitHub Desktop.
This is in-regard to a comment someone made about having a triple nested return for "getInstance".
define([ 'utils/Singleton' ],
function(Singleton) {
'use strict';
var MyClass;
MyClass = (function() {
function MyClass() {}
MyClass.prototype.methodA = function() {};
MyClass.prototype.methodB = function() {};
MyClass.prototype.methodC = function() {};
return MyClass;
})();
return Singleton(MyClass);
});
function Singleton(classInstance) {
var __instance = null;
return {
getInstance: function() {
if (__instance === null) {
__instance = new classInstance();
}
return __instance;
}
};
}
@benbabics
Copy link
Author

No worries, Dan. You're completely right, the class Singleton itself is not the Singleton, rather it just wraps the class passed into it as a Singleton by managing .getInstance() calls with __instance. Now, you're completely right that __instance would be null every time with each call to Singleton, however, using this in combination with RequireJS means that our class is modularized, so each time this module (Class) is required as a dependency for another module, it is being guarded by the call to Singleton; it isn't a new call Singleton every time. Each time it's required the dependent is only being returned .getInstance() which guards the Class.

This wouldn't work so well outside of being an AMD module which, I think, is what was throwing you through a loop.

@benbabics
Copy link
Author

Additionally, if you're not using this within a module, the return for the self-invoking anonymous function would then be return Singleton(MyClass); instead of simply return MyClass;

So, it would look something like:

var MyClass;
MyClass = (function() {
...
return Singleton(MyClass);
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment