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
37.5k13 gold badges85 silver badges100 bronze badges
asked Feb 10, 2010 at 7:42
2

5 Answers 5

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);
answered Feb 10, 2010 at 7:45
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Feb 10, 2010 at 7:44

Comments

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

answered Feb 10, 2010 at 7:46

Comments

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.

answered Feb 10, 2010 at 7:45

Comments

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
53.8k68 gold badges198 silver badges291 bronze badges
answered Feb 10, 2010 at 7:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.