How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?(这个 JavaScript/jQuery 语法是如何工作的:(function(window, undefined) { })(window)?)
问题描述
你有没有看过 jQuery 1.4 源代码的底层并注意到它是如何以下列方式封装的:
Have you ever taken a look under the hood at the jQuery 1.4 source code and noticed how it's encapsulated in the following way:
(function( window, undefined ) {
//All the JQuery code here
...
})(window);
我读过一篇关于 JavaScript 命名空间 的文章和另一篇名为一对重要的 Parens," 所以我知道发生了什么这里.
I've read an article on JavaScript Namespacing and another one called "An Important Pair of Parens," so I know some about what's going on here.
但我以前从未见过这种特殊的语法.undefined
在那里做什么?而为什么window
需要经过,然后又出现在最后?
But I've never seen this particular syntax before. What is that undefined
doing there? And why does window
need to be passed and then appear at the end again?
推荐答案
undefined是一个普通变量,可以通过undefined = "new value";
简单地改变.所以 jQuery 创建了一个真正未定义的本地未定义"变量.
The undefined is a normal variable and can be changed simply with undefined = "new value";
. So jQuery creates a local "undefined" variable that is REALLY undefined.
出于性能原因,window 变量是本地变量.因为 JavaScript 在查找变量时,首先会遍历局部变量,直到找到变量名.如果没有找到,JavaScript 会遍历下一个作用域等,直到它过滤掉全局变量.因此,如果 window 变量是本地的,JavaScript 可以更快地查找它.更多信息:加速 JavaScript - Nicholas C. Zakas
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
这篇关于这个 JavaScript/jQuery 语法是如何工作的:(function(window, undefined) { })(window)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:这个 JavaScript/jQuery 语法是如何工作的:(function(window, undefined) { })(window)?
基础教程推荐
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 我什么时候应该在导入时使用方括号 2022-01-01
- 动态更新多个选择框 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01