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

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

提交回复
热议问题