Skip to content

Instantly share code, notes, and snippets.

@jasonwyatt
Created July 26, 2011 15:09
Show Gist options
  • Save jasonwyatt/1106973 to your computer and use it in GitHub Desktop.
Save jasonwyatt/1106973 to your computer and use it in GitHub Desktop.
Singleton Pattern with Require JS
define(function(){
var instance = null;
function MySingleton(){
if(instance !== null){
throw new Error("Cannot instantiate more than one MySingleton, use MySingleton.getInstance()");
}
this.initialize();
}
MySingleton.prototype = {
initialize: function(){
// summary:
// Initializes the singleton.
this.foo = 0;
this.bar = 1;
}
};
MySingleton.getInstance = function(){
// summary:
// Gets an instance of the singleton. It is better to use
if(instance === null){
instance = new MySingleton();
}
return instance;
};
return MySingleton.getInstance();
});
@layton-glympse
Copy link

layton-glympse commented May 16, 2016

@jasonwyatt Out of curiosity, is there a reason that getInstance is even necessary? Why can't we just have the constructor point to _instance and return that if it's not null? I.e., here is my revised version that seems to return the same object every time. Note that it makes use of the fact that you can use a constructor to return anything you want.

define(function(require, exports, module)){
    var _instance = null;

    function MySingleton() {
        //You can retrofit this to support calling init() where necessary... just keeping it brief :)
        _instance = _instance === null ? this : _instance;
        return _instance;
    }

    module.exports = MySingleton;
});

Seems to work for me... any reason you think this wouldn't be equivalent output-wise to yours? The upside to this is that it conforms more to the requirejs ecosystem and is easier to read.

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