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

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

    If forces scope declaration. By putting it in a function you are making sure that the variables you create and call aren't being re-declared or you aren't accidentally calling variables which are declared elsewhere.

    so.....

    var variable = 5; // this is accessible to everything in the page where:
    
    function ()
    {
       var variable = 7 // this is only available to code inside the function.
    }
    

    Here is a link to Douglas Crockford's site talking about scope in Javascript:

    http://javascript.crockford.com/code.html

    to follow up on the comment below:

    JavaScript's scope is a little "broken":

    function ()
    {
       var x = 3;  // accessible in the entire function.
       //for scope reasons, it's better to put var y = 8 here.....
       if(x != 4)
       {
           var y = 8; //still accessible in the entire function. 
                      //In other languages this wouldn't be accessible outside 
                      //of the if statement, but in JavaScript it is.  
    
       }
    
    }
    

提交回复
热议问题