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

前端 未结 4 996
遇见更好的自我
遇见更好的自我 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:42

    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. e.g:

    (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.

    0 讨论(0)
  • 2020-12-01 21:45

    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.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-12-01 21:47

    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

    0 讨论(0)
提交回复
热议问题