Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is benefit of using (function(){...})() in JavaScript

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?

like image 860
Alan Avatar asked Feb 03 '23 06:02

Alan


1 Answers

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

  • http://docs.jquery.com/Plugins/Authoring

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);
like image 106
Tatu Ulmanen Avatar answered Feb 05 '23 20:02

Tatu Ulmanen