Did somebody come up with this pattern so it is a famous and well-known pattern?
I see this pattern for using Javascript / jQuery, such as in init.js:
var Initializations = {};
Initializations = (function($) {
function doSomething(i, domElement) {
// ...
}
$(function() {
$("#foo").click(function() {
// ...
});
$(".bar").each(doSomething);
});
})(jQuery);
So it looks like it can “hide” almost everything from the global scope, avoid conflict if another library also uses $ as a variable, and the HTML page can be altered by this code using jQuery. The code does almost nothing to the global scope (except the variable Initializations), and even if there are
2 jQuery versions, and if they can be denoted by 2 variables jQuery142 and jQuery161, then the code can be even using 2 jQuery libraries just by changing the last line of the code above
to jQuery161 (say, if some 3rd party code needs jQuery 1.4.2 and your code has been using jQuery 1.6.1 for new features and/or bug fixes).
Can the above code be improved? I am wondering why the extra variable Initializations, why not just:
(function($) {
function doSomething(i, domElement) {
// ...
}
$(function() {
$("#foo").click(function() {
// ...
});
$(".bar").each(doSomething);
});
})(jQuery);
?
Take a look at Crockford’s pattern and the Revealing Module Pattern. They are similar to what you posted but go a bit further and show why you’d want to namespace with the Initializations var.