Init function in javascript and how it works

前端 未结 7 1859

I often see the following code:

(function () {
  // init part
})();

but I never could get my head around how it works. I find the last brac

7条回答
  •  爱一瞬间的悲伤
    2020-12-02 06:27

    I can't believe no-one has answered the ops question!

    The last set of brackets are used for passing in the parameters to the anonymous function. So, the following example creates a function, then runs it with the x=5 and y=8

    (function(x,y){
        //code here
    })(5,8)
    

    This may seem not so useful, but it has its place. The most common one I have seen is

    (function($){
        //code here
    })(jQuery)
    

    which allows for jQuery to be in compatible mode, but you can refer to it as "$" within the anonymous function.

提交回复
热议问题