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

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

    JavaScript doesn't have block scoping, only function scoping. By creating and immediately invoking an anonymous function, we can guarantee that its local variables won't step all over the global namespace. It's basically a way to limit conflicts with other libraries that may be in play.

    0 讨论(0)
  • 2021-02-05 16:09
    var $={} // a name space is defined 
    
    (function($) {
            $.a_variable="some vale"
            var b_variable = "some more value";
    })($);
    
    $.a_variable // acess it like this.
    

    now any thing inside anonymous function has scope equal to that function only also we can create objects that may act as properties to our name space.

    0 讨论(0)
  • 2021-02-05 16:12

    At a simple level it keeps the global namespace clean(er).

    i.e.: It's effectively adding a layer of wrapping around the functions and variables within the library hence ensuring there aren't any namespace clashes with other functions that may be in use from other libraries, etc.

    0 讨论(0)
  • 2021-02-05 16:16

    This is standard way to do namespacing in JavaScript. If you just declare

    var my_cool_variable = 5;
    

    it will be global and might conflict with other libraries, that use the same variable.

    However, if you do

    (function() {
        var my_cool_variable = 5;
    })();
    

    it is now local variable for anonymous function and is not visible outside of the scope of that function. You still can expose accessible API by not stating var in front of variable, that way it will be global but now you have a choice.

    0 讨论(0)
  • 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.  
    
       }
    
    }
    
    0 讨论(0)
提交回复
热议问题