Init function in javascript and how it works

前端 未结 7 1853

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:23

    The code creates an anonymous function, and then immediately runs it. Similar to:

    var temp = function() {
      // init part
    }
    temp();
    

    The purpose of this construction is to create a scope for the code inside the function. You can declare varaibles and functions inside the scope, and those will be local to that scope. That way they don't clutter up the global scope, which minimizes the risk for conflicts with other scripts.

提交回复
热议问题