Instant Call Function (IIFE) Expression in JavaScript - jQuery Pass

I have the following code that I know is IIFE. However, I could never understand what (jQuery) and ($) are. I know this is due to passing the jQuery reference to IIFE, but can anyone explain their purpose to me? Thank you for your help and time :-)

(function ($) { //code })(jQuery); 
+6
javascript jquery iife
Sep 08 '12 at 16:14
source share
1 answer

$ is an argument to a function. jQuery is what is passed as this argument when the function is called.

Think of it this way:

 function init($) { // code can use $ here as a shortcut for jQuery // even if $ has a different definition globally or isn't defined globally } init(jQuery); 

Except this example creates a global init symbol, the execution of this and your IIFE are identical. Both define a function and immediately call it.

$ is an argument to a function. jQuery is what is passed as this argument. This serves to define $ as a shortcut to jQuery inside this function without affecting the global definition of $ . Sometimes there can also be a slight performance advantage, since characters defined locally (both local variables and named arguments) can be slightly faster than global characters.

The advantage of IIFE is that new global characters are not defined. In addition, it is identical when executing this code.

+13
Sep 08 '12 at 16:16
source share



All Articles