Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - a simple question on jquery closure

what does this mean?

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

to make the question clearer, what does wrapping a function in parenthesis mean in JS (sorry, I'm a bit confused on the concept of closures). What about the $ parameter? and the "jQuery" in the end parenthesis?

Can I do the same with mootools and combine them in 1 JS file?

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

(function($){})(mooTools);

I have only worked with jquery and am planning to work with Mootools

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Wrapping a function between parenthesis ensures this function to be evaluated as a function expression.

That happens because the Grouping Operator (the parentheses), can only evaluate expressions.

If no parenthesis are used, it will be interpreted as a function declaration, and it will cause a syntax error, since the function name is not optional for function declarations.

(function(arg){
  alert(arg); // alerts test
})("test");

In the above example, the function expression is automatically executed, passing an argument.

That pattern is heavily used by jQuery plugins, since jQuery can run in noConflict mode, the $ global variable will not be created, so the jQuery global object is passed as an argument of this anonymous function and inside of that function, you can freely refer to it as $ (the received argument).

Keep in mind that also, the function context (the this keyword) inside self-executing function expressions invoked like the above example, will refer always to the Global object.

For a more in-depth info about the differences between function expressions and function declarations, give a look to the following resources:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...