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

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

    JavaScript doesn't have block scoping, only function scoping. By creating and immediately invoking an anonymous function, we can guarantee that its local variables won't step all over the global namespace. It's basically a way to limit conflicts with other libraries that may be in play.

提交回复
热议问题