0

Possible Duplicate:
What does this JavaScript/jQuery syntax mean?

I specifically mean when you do this:

(function ($) {
  ...
})(jQuery);

I've never seen that kind of syntax before. How does the function get called? I understand when you do it like this:

jQuery(function ($) {
  ...
});

because the function is being passed to jQuery, and jQuery can just run any function passed as a parameter when the DOM's ready, but the first one's different.

Community
  • 1
  • 1
Nathan MacInnes
  • 11,033
  • 4
  • 35
  • 50

2 Answers2

4

Duplicate of What does this JavaScript/jQuery syntax mean?

I'll post my answer here, though seeing as Jeff Attwood seems to want us to embrace duplication: (https://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/)


This convention is used when writing plugins to ensure there is no confilict with other Javascript libraries using the $ notation, whilst ensuring the plugin author can still use this notataion:

(function($){
    ...
})(jQuery); 

The author is declaring an anonymous function with a single parameter ($), then immediately calling it and passing the jQuery object to it. This ensures the function is called and that everything in it is defined.

A longer notation might be:

function MyDefs($){
    ...
}
MyDefs(jQuery);

Although that would create a variable MyDefs in the global namespace. The anonymous function pattern leaves the global namespace empty, avoiding conflicts.

Community
  • 1
  • 1
James Wiseman
  • 29,946
  • 17
  • 95
  • 158
1

It's an anonymous function. When you write:

(function ($){
  ..
})(jQuery);

It is mostly equivalent to:

function the_function($) {
  ..
}

the_function(jQuery);

The only difference being that the first does not create a function called the_function and therefore created no risk of accidentally overwriting an existing function or variable with that name. And of course, all of it is equivalent to:

function the_function() {
  var $ = jQuery;
  ..
}

the_function();

The point of this construct is that any variables defined inside the_function are local and therefore cannot accidentally overwrite any variables or functions in the global scope. For instance, the code inside the function uses $ to represent the jQuery object, but this would conflict with other libraries that use $ as well (such as Prototype). By wrapping the usage of $ inside a function, the Prototype code outside the function remains unaffected.

Victor Nicollet
  • 24,361
  • 4
  • 58
  • 89