您是否曾仔细查看过jQuery 1.4个源代码,并注意到它是如何以以下方式封装的:

(function( window, undefined ) {

  //All the JQuery code here 
  ...

})(window);

我读过一篇关于JavaScript Namespacing的文章和另一篇叫做"An Important Pair of Parens"的文章,所以我对这里的情况有所了解.

但我以前从未见过这种特殊的语法.那100人在那里干什么?为什么101需要通过,然后再次出现在末尾?

推荐答案

undefined是一个正态变量,只需使用undefined = "new value";即可更改.因此jQuery创建了一个真正未定义的局部"未定义"变量.

The window variable is made local for performance reasons. Because when JavaScript looks up a variable, it first goes through the local variables until it finds the variable name. When it's not found, JavaScript goes through the next scope etc. until it filters through the global variables. So if the window variable is made local, JavaScript can look it up quicker. Further information: Speed Up Your JavaScript - Nicholas C. Zakas

Jquery相关问答推荐

使用 shell 脚本判断 json 数组响应是否具有特定用户名和状态的 jq 命令

DataTables - this.api 用于回调函数中的多个表

Sheets从多张sheet中导入range匹配数据

Bootstrap 的工具提示在悬停时将表格单元格向右移动一点

在jQuery中获取所有选定复选框值的最佳方法

如何设置缓存:jQuery.get 调用中的 false

在 Javascript 中,字典理解或 Object `map`

jQuery JSON到字符串?

scrollIntoView 是否适用于所有浏览器?

使用 时如何从 select2 中获取选定文本

使用 jQuery 从 AJAX 响应(json)构建表行

在jQuery中将逗号添加到数字

停止输入/书写后如何触发输入文本中的事件?

jQuery:如何找到第一个可见的输入/ Select /文本区域,不包括按钮?

在ajax请求中检测重定向?

页面加载后如何执行jquery代码?

通过 javascript/jquery 删除/截断前导零

jquery - 从一个非常大的表中删除所有行的最快方法

使用 jQuery 在 Select 列表中隐藏选项

为什么要定义一个匿名函数并将 jQuery 作为参数传递给它?