这个JavaScript / JQuery语法如何工作:( function(window,undefined){})(window)? [英] How does this JavaScript/JQuery Syntax work: (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
在那里做什么?为什么需要传递 窗口
,然后再次出现?
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.
由于性能原因,窗口变量是本地的。因为当JavaScript查找变量时,它首先遍历局部变量,直到找到变量名称。如果找不到它,JavaScript将通过下一个范围等,直到它过滤全局变量。因此,如果窗口变量是本地的,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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!