1

Possible Duplicate:
For the function (function($){})(), I’ve seen it with the word jQuery in it, why is that?

Can someone explain the following syntax that is used in the jQuery source files? I am learning jQuery and trying to dive into writing a jquery.ui.widget.

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

While I am using jQuery, this is really just a JavaScript question, I guess.

Thanks, Craig

Community
  • 1
  • 1
Craig Celeste
  • 12,207
  • 10
  • 42
  • 49
  • 2
    See a similar question from yesterday: http://stackoverflow.com/questions/3090284/for-the-function-function-ive-seen-it-with-the-word-jquery-in-it-why – Christian C. Salvadó Jun 23 '10 at 20:14
  • Indeed JavaScript-related, see http://stackoverflow.com/questions/1643321/javascript-why-the-anonymous-function-wrapper among many others. – Marcel Korpel Jun 23 '10 at 20:15

3 Answers3

7

This defines an anonymous function with one argument, called $, then invokes the function passing jQuery as the argument.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
1

It's called the self executing anonymous function. No different than any other function call except the function is a literal ( doesnt have a name ), is wrapped in parens to make it a valid expression and then invoked.

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

is the same as that piece of code, it creates a private namespace in which the window.jQuery object is passed and referenced within the function body as $ to prevent namespace collisions.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
1

This is an example of the JavaScript module pattern.

Scott Bale
  • 10,649
  • 5
  • 33
  • 36