为什么要在函数定义 - 调用对中编写全局代码? [英] Why would one write global code inside a function definition-call pair?

查看:114
本文介绍了为什么要在函数定义 - 调用对中编写全局代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

而不是:

// do something

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

I first thought this is just for local scoping, i.e. creating local variables for the code block without polluting global namespace. But I've seen instances without any local variables at all too.

我在这里缺少什么?

推荐答案

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

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

这篇关于为什么要在函数定义 - 调用对中编写全局代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆