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

前端 未结 4 1114
遇见更好的自我
遇见更好的自我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题