Why do many javascript libraries begin with “(function () {”?

前端 未结 5 1552
清歌不尽
清歌不尽 2021-02-05 15:55

Why do many javascript libraries look like this:

(function () { 
    /* code goes here */ 
})();

It appears to define an unnamed function whic

5条回答
  •  青春惊慌失措
    2021-02-05 16:16

    This is standard way to do namespacing in JavaScript. If you just declare

    var my_cool_variable = 5;
    

    it will be global and might conflict with other libraries, that use the same variable.

    However, if you do

    (function() {
        var my_cool_variable = 5;
    })();
    

    it is now local variable for anonymous function and is not visible outside of the scope of that function. You still can expose accessible API by not stating var in front of variable, that way it will be global but now you have a choice.

提交回复
热议问题