这个 JavaScript/jQuery 语法是如何工作的:(function(window, undefined) { })(window)?

2022-01-30 00:00:00 syntax jquery javascript

你有没有看过 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

相关文章