简体   繁体   中英

What is the purpose of this? (function ($) { //function code here })(jQuery);

I am debugging someone else's JavaScript code and a majority of the code is wrapped like this:

(function ($) {
    //majority of code here...
})(jQuery);

What is going on with the ($) and the (jQuery) ? I wasn't taught to code like that and haven't seen them. What is their purpose?

As well, there is no document.ready , but I assume that is because the code is executed right after it's read by the (); at the end?

var $ = "some value we don't care about";

 // v=====normal plain old function
(function ($) {
 //        ^=======receives jQuery object as the $ parameter

    //majority of code here, where $ === jQuery...

    $('.myclass').do().crazy().things();


})(jQuery);
 //  ^=======immediately invoked, and passed the jQuery object


 // out here, $ is undisturbed
alert( $ ); // "some value we don't care about"

This is useful when you want / need to use jQuery.noConflict() , and the global name $ isn't an alias for jQuery. The code you posted lets you use the shorter $ to mean jQuery inside the anonymous function only, without $ needing to be a global.

Just to expand on RightSaidFred's answer a little, when I first saw the ()() syntax I was a bit befuddled, but it made sense once I realised the brackets are being used to define an anonymous function and then call it. eg:

(function (msg){alert(msg)})('hello');

... defines a function and then calls it, passing 'hello' as a parameter.

So the example in the question:

(function ($) {
    //majority of code here...
})(jQuery);

is passing jQuery into an anonymous function and referring to it as $ within the function, a way of guaranteeing that $ will work for jQuery without interfering with anything else.

This structure is called JQuery Plugin, purpose of the plugins is to create a framework of any common task/function in your project, same-way you can extend your plugins according to your usage in different page or in same page. that way you can avoid repeating the same code everywhere.

check it out http://docs.jquery.com/Plugins/Authoring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM