Why would one write global code inside a function definition-call pair?

后端 未结 5 1660
轮回少年
轮回少年 2020-12-19 08:27

I see examples where JavaScript code including jQuery and jslint use the notation below:

(function(){
  // do something
})();

instead of:

5条回答
  •  情书的邮戳
    2020-12-19 09:00

    It's about scope for functions, too - everything declared within the code block is scoped to that anonymous function only. Things are normally made public by the framework

    (function($) {
    
      var localVarOnly = "local";
    
      $.fn.myCoolFunction = function() { // in the case of jquery, make this publicly available
        otherCoolFunction(); //alerts hi
        alert(localVarOnly); // alerts local
      };
    
      function otherCoolFunction() { // scoped to this anonymous function only
        alert('hi');
      };
    
    })(jQuery);
    
    otherCoolFunction(); // undefined
    alert(localVarOnly); // undefined
    

提交回复
热议问题