What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

后端 未结 8 1693
轮回少年
轮回少年 2020-11-22 02:02

I have been reading a lot of Javascript lately and I have been noticing that the whole file is wrapped like the following in the .js files to be imported.

(f         


        
8条回答
  •  你的背包
    2020-11-22 02:36

    Javascript in a browser only really has a couple of effective scopes: function scope and global scope.

    If a variable isn't in function scope, it's in global scope. And global variables are generally bad, so this is a construct to keep a library's variables to itself.

提交回复
热议问题