为什么要在函数定义 - 调用对中编写全局代码?

Sed*_*glu 6 javascript

我看到包含jQuery和jslint的JavaScript代码使用下面的符号的示例:

(function(){
  // do something
})();
Run Code Online (Sandbox Code Playgroud)

代替:

// do something
Run Code Online (Sandbox Code Playgroud)

我首先想到的只是本地范围,即为代码块创建局部变量而不会污染全局命名空间.但我见过没有任何局部变量的实例.

我在这里错过了什么?

Dan*_*den 8

它也是关于函数的范围 - 代码块中声明的所有内容仅限于该匿名函数.事情通常由框架公开

(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
Run Code Online (Sandbox Code Playgroud)