9

I noticed in JQuery that the following code structure is used

(function(){var l=this,g,y=l.jQuery,p=l.$,...})()

Which seems to create a function, and call it.

What is the benefit of taking this approach versus having the contents of the function inline?

Jimmy
  • 35,686
  • 13
  • 80
  • 98
Alan
  • 2,140
  • 1
  • 24
  • 30
  • 1
    Duplicate: http://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript – Tim Down Feb 10 '10 at 09:53
  • This one as well: http://stackoverflow.com/questions/631187/javascript-scope-and-closure The problem is that the findability of these questions/answers is not good. If all I know is "[javascript] (function()", then search does not do a good job finding anything useful. – Alan Feb 10 '10 at 19:07

5 Answers5

7

It creates a closure to prevent conflicts with other parts of code. See this:

Particularly handy if you have some other library that uses the $() method and you have to retain the ability to use that with jQuery also. Then you can create a closure such as this:

(function($) {
    // $() is available here
})(jQuery);
Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
4

It creates a scope for variables, in particular defining $ for example to bind to jQuery, no matter what other libraries overwrite it. Think of it as an anonymous namespace.

Blindy
  • 65,249
  • 10
  • 91
  • 131
1

With self invoking anonymous function you create a local scope, it's very efficient and it directly calls itself.

You can read about it here

Juraj Blahunka
  • 17,913
  • 6
  • 34
  • 52
0

It's just like:

var foo = function(){var l=this,g,y=l.jQuery,p=l.$,...};
foo();

But more simple and do not need a global variable.

XUE Can
  • 701
  • 6
  • 8
0

It allows to have local variables and operations inside of the function, instead of having to transform them to global ones.

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
Valentin Rocher
  • 11,667
  • 45
  • 59