-4

In order to use the $ symbol in jquery and not have to use jQuery.functionname, we use this

(function($) {

})(jQuery);

(In drupal, you actually have to specify this implicitly).

I don't understand this javascript syntax, why is there an initial parentheses? How is the (jQuery) at the end used?

user1015214
  • 2,733
  • 10
  • 36
  • 66
  • 6
    It's an *immediately invoked anonymous function expression.* Has been discussed untold times before. `$` is simply a variable name. – deceze Oct 30 '13 at 16:46
  • the first function variable is $ and then you're calling it passing jQuery....and what he said ^ – rorypicko Oct 30 '13 at 16:47
  • I'm sure I was discussed elsewhere, but I didn't know how to look it up. I looked up immediate invoked javascript and now I found the answer. Thanks. – user1015214 Oct 30 '13 at 16:49
  • Understand closure [here](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Murali Murugesan Oct 30 '13 at 16:50
  • @deceze It's not necessarily easy to find that information if you don't know what the construct is called (and why would you if you don't know what it is), though. – Anthony Grist Oct 30 '13 at 16:51
  • Self executing ananymous function which passes `jQuery` as parameter – Murali Murugesan Oct 30 '13 at 16:51
  • @Anthony Admittedly, yes, absolutely. But some random googling and poking around should have let to that conclusion sooner or later IMO. – deceze Oct 30 '13 at 18:56

2 Answers2

1

It's just an anonymous function with an argument that's automatically invoked.

For example, if we were to expand it out a bit you'd end up with something like this:

var anon = function($) {
    ...
};

anon(jQuery);

The $ is a valid identifer in JavaScript and we pass in the existing jQuery object into the function for use through $, as it could be replaced later.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
0

All that's doing is declaring an anonymous function and executing it immediately, passing in one argument (jQuery) into the function. That argument is given the name $ which can be used throughout the scope of the function.

The brackets around the function aren't strictly necessary in all contexts; see the comment under this answer for details. The gist is that they're needed here to make the function behave like an expression instead of a statement (function declaration).

Community
  • 1
  • 1
mpen
  • 272,448
  • 266
  • 850
  • 1,236