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

前端 未结 5 1549
清歌不尽
清歌不尽 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:12

    At a simple level it keeps the global namespace clean(er).

    i.e.: It's effectively adding a layer of wrapping around the functions and variables within the library hence ensuring there aren't any namespace clashes with other functions that may be in use from other libraries, etc.

提交回复
热议问题