I was reading this article about the module Javascript pattern, but I don’t understand what is the benefit of the “Global import”.
What is the difference between:
(function () {
alert($('#theForm').attr('method'));
} ());
and
(function ($) {
alert($('#theForm').attr('method'));
} (jQuery));
Both methods has the same effect, so I think I am missing the point here.
What is the point of pass global variables as parameters in the anonymous closure? what are the benefits?
Lots of scripts (such as Prototype and Mootools) also use the
$character. It is therefore sometimes useful to not use that character on a global level. You can do this in jQuery by usingjQuery.noConflict(). You then have to usejQueryto do jQuery selections and the like.If, however, you have a section of code (a “module”, perhaps) that you know will only use jQuery, you can redefine
$for that section of code only using that pattern. The object known asjQueryoutside the function is now known as$inside the function: