开发者

Anonymous closures and global imports

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 using jQuery.noConflict(). You then have to use jQuery to 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 as jQuery outside the function is now known as $ inside the function:

(function($) { // the first parameter is known as $
    // inside the function, you can access jQuery by the name $
}(jQuery)); // pass jQuery as the first argument


By the second version, you are ensuring that you may use the dollar-sign $ for jquery. Otherwise, you could get into trouble, when you import a second javascript library that also uses the dollar sign as an alias (prototype for example).

So by the second version, you always ensure there will be no conflicts, by passing in the unique name (jQuery in this case).


A simplified example to explain this would be as follows.

var jqueryCloneLibrary = {libName : 'jqClone_1.1.1',size : '4kb'}; // 
(function(_){console.log(_.libName,_.size)}(jqueryCloneLibrary)) 

Above, a clone on global level has been declared and stored as a reference in var jqueryCloneLibrary.

The reference to the object i.e jqueryCloneLibrary is passed as an argument to the IIFE (immediately invoked function)

Inside the function definition, we have the parameter defined as an _ using which we are able to access the properties _.name and _.size.

We include jquery or any other library the similar way and this is known as a Global Import.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜