These two JavaScript patterns are very similar. I would like to know which one is better and why and how either one can be improved.
First Approach:
"MODULE" in window || (window.MODULE = {} );
MODULE.utils = (function ($) {
var utils = {};
//public
utils.todo = function() {
//#
}
//private
function init() {
//#
}
init();
return utils;
}(jQuery));
Second Approach:
"MODULE" in window || (window.MODULE = {} );
MODULE.utils = (function() {
function todo(){
//#
}
function init() {
//#
}
return {
init:init
}
})();
$(function() {
MODULE.utils.init();
});
Both of your options don’t really have much in the way of pros or cons, it’s more just about personal preference. Both could be adjusted to provide scope a bit better.
I have my own preference, it relies on Underscore. It doesn’t really promote private variables or functions but I rarely find this an issue. If you want to introduce jQuery, etc, it would be best to wrap in an anonymous function to
$is actuallyjQuery(or an interchangeable library).As you’ll see below, my preference requires a little more code to get you going (although some of it’s not necessary), but having tried a few variations of what you originally proposed, I’ve found that my solutions lends itself to more understandable code and it’s easier for other devs to get the grasp of what’s going on, especially if they’ve got experience with
Backbone.View.EDIT: Wrapped in an anonymous function to demonstrate integrating jQuery and protected scope.