(function( $ ){
MY_SINGLETON_OBJ = MY_SINGLETON_OBJ || (function () { // initialize the singleton using an immediate anonymous function which returns an object
// init here (only happens once even if this plugin is included multiple times)
console.log("Initialized");
return {
version: "0.1"
// return values that are to be accessible from the singleton
};
})();
$.fn.MyJqueryObjectMethod = function (a, b, c) {
// perform tasks
return this; // maintain chainability
};
})(jQuery);
The singleton is polluting the global namespace. Is there a better way to define it?
That looks to me like it would work, though I think you should at least declare your singleton globally rather than use an implicit definition.
You don’t have to be that tricky. You can just as easily do this which I think it a bit more readable and obvious: