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

前端 未结 4 1111
遇见更好的自我
遇见更好的自我 2020-12-01 21:13

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

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


        
4条回答
  •  臣服心动
    2020-12-01 21:46

    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"
    

提交回复
热议问题