7

I have the following plugin:

;(function($, window, document)
{
...
...

})(jQuery, window, document);

I can understand what the ; is for and also realize that $ is the jQuery but can someone explain why is the function followed by (jQuery, window, document);

5 Answers5

11

It's called a 'self ivoking' or 'immediately invoked' function. It means that the function is run as soon as it is created using the parameters in the final set of brackets.

Further information

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
4

This is called Immediately-Invoked Function Expression or Self-executing anonymous function. It enables the developer to hide his private declarations.

;(                                 // <---------------+
                                   //                 | encapsulate the function
  function($, window, document) {  // <--+ declare    | and call it passing three
                                   //    | anonymous  | arguments.
  }                                // <--+ function   |
                                   //                 |
)(jQuery, window, document);       // <---------------+
Florent
  • 12,310
  • 10
  • 49
  • 58
3

I'm not sure I fully understand what you are asking, but what they do is that they pass the jQuery object, the window object and the document object to the function.

Most likely they do this for performance reasons. This makes it possible for a minimizer to shorten all the references to window and document to something like w and d, since it is local variables. In a large library, that could save a few bytes.

Additionally I believe (have no reference atm) that it is slightly faster to access a local variable, compared to a global variable (really a micro optimization though).

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
1

It's an Immediately-Invoked Function Expression

That means, the function is declared and executed right away. This this done in order to create a new scope.

Prinzhorn
  • 22,120
  • 7
  • 61
  • 65
1

It's an anonymous function that's immediately invoked (the so called IIFE).

The passing of jQuery aliases it to $, and window and document so they can be sure the reference is to the correct version in the outside environment.

alex
  • 479,566
  • 201
  • 878
  • 984