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;
}
};
}
@kfd-johnson
Copy link

I still don't quite understand the scoping. It seems that the function Singleton cannot be a singleton because you could never create more than one singleton. Say i wanted a singleton of type a and type b. I don't see how that could happen if Singleton were a singleton. On the other hand if Singleton is not a singleton then i would think that __instance is scoped to every call of Singleton i.e. a new variable __instance is created every time you call Singleton. But if that is the case they you won't get a singleton of classInstance because __instance would always be null and thus you would create a new instance of classInstance every time.

@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