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

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

提交回复
热议问题