这个 JavaScript/jQuery 语法是如何工作的:(function( window, undefined ) { })(window)? [英] How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?

查看:27
本文介绍了这个 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 Namespacing 的文章和另一篇名为一对重要的父母,"所以我知道一些继续在这里.

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.

出于性能原因,窗口变量被设置为本地变量.因为当 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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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