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

后端 未结 8 1689
轮回少年
轮回少年 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.
    0 讨论(0)
  • 2020-11-22 02:43

    That's called a closure. It basically seals the code inside the function so that other libraries don't interfere with it. It's similar to creating a namespace in compiled languages.

    Example. Suppose I write:

    (function() {
    
        var x = 2;
    
        // do stuff with x
    
    })();
    

    Now other libraries cannot access the variable x I created to use in my library.

    0 讨论(0)
提交回复
热议问题