0

I'm reading up on jQuery plugins, and in the official guide the author states:

"But wait! Where's my awesome dollar sign that I know and love? It's still there, however to make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution."

Here is the example code:

(function( $ ) {
    $.fn.myPlugin = function() {

        // Do your awesome plugin stuff here

    };
})( jQuery );

My question is, why is the IIFE necessary, and what are some examples of collisions that could occur without it? Upon execution, the $ parameter will be replaced by the Jquery global variable, and therefore a global variable is being altered by the IIFE. To me, that seems to suggest that collisions are just as likely as before. I know I'm missing something here. Many thanks in advance for your help!

Musa
  • 96,336
  • 17
  • 118
  • 137
voltair
  • 615
  • 2
  • 7
  • 21

2 Answers2

1

The $ symbol is used as a global variable by other libraries such as prototype and MooTools. Therefore the $ global variable might not refer to jQuery; this is the reason jQuery's noConflict method exists.

So if your plugin was to be used on a page that utilizes either prototype or MooTools in addition to jQuery, you cannot be sure that $ will be referring to jQuery, but you can assume that the jQuery variable will. If you're writing a plugin you want to make it as easy as possible for others to use. Therefore you want to make it seamless for use with other libraries.

The IIFE makes it possible to have this safety and still have the convenience of using $ in your code. If you're fine always referring to the jQuery library with the jQuery reference instead of $ then the IIFE is unnecessary.

TJ VanToll
  • 12,584
  • 4
  • 43
  • 45
0

Imagine that some other library "steals" the $ global variable (by assigning its own library object to it):

$ = otherLibrary;

Now, $ refers to that other library, but jQuery (which is also a global variable) still refers to the jQuery library.

If your plug-in is written like this:

$.fn.myPlugin = function () { ... };

it won't be assigned to jQuery's $.fn object since $ doesn't refer to the jQuery library anymore.

However, if your plug-in is written like this:

(function ( $ ) {
    $.fn.myPlugin = function () { ... };
}( jQuery ));

it will be assigned to jQuery's $.fn object since the (local) argument $ is a reference to the global variable jQuery.

So:

$ === jQuery // false

(function ( $ ) {

    $ === jQuery // true

    $.fn.myPlugin = function () { ... };

}( jQuery ));

$ === jQuery // false

The argument $ is shadowing the global variable $ (which refers to the other library).

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385