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

后端 未结 8 1690
轮回少年
轮回少年 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:41

    1. To avoid clash with other methods/libraries in the same window,
    2. Avoid Global scope, make it local scope,
    3. To make debugging faster (local scope),
    4. JavaScript has function scope only, so it will help in compilation of codes as well.

提交回复
热议问题