Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...