为什么这两个参数在jQuery源代码中? [英] Why are these two parameters in the jQuery source for?

查看:80
本文介绍了为什么这两个参数在jQuery源代码中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery源包装在一个闭包中,如下所示:

 (function(window,undefined){
//这里有很棒的jQuery库代码
})(window);

我不明白为什么需要这些参数。



由于窗口是一个全局变量,为什么需要传入?传递一个全局参数并在闭包内使用相同名称访问它的目的是什么?



什么是 undefined 参数为?为什么没有传递给它的任何值?

解决方案

我很确定这已经得到了答案,但是:




  • 传入窗口 a)允许代码压缩来篡改名称(即在匿名函数中用单字母变量名替换它)和b)确保变量在定义库时引用窗口对象,以防有人重新定义 window 加载jQuery后的全局范围。


  • 包括 undefined 作为参数(但不是传入一个值)对 undefined 做同样的事情,允许变量重组并避免在重新定义 undefined 变量时出现问题(是的,Javascript允许这样做)。




我相信这两种情况都应该加快对变量的引用,因为它使两个全局变量在函数范围内可用,其中int erpreter会在查看全局范围之前进行搜索。但我不能诚实地想象这里的性能差异很大 - 我认为最大的问题是变量名称munging,这使得缩小代码时更加紧凑。


The jQuery source is wrapped in a closure, like this:

(function(window, undefined) {
   //awesome jQuery library code in here
})(window);

I don't understand why either of these parameters are needed.

Since window is a global variable, why does it need to be passed in? What's the purpose of passing in a global parameter and accessing it inside the closure with the same name?

What's the undefined parameter for? Why isn't any value passed to it?

解决方案

I'm pretty sure this has been answered already, but:

  • passing in window a) allows code compression to munge the name (i.e. replacing it with a single-letter variable name within the anonymous function) and b) ensures that the variable references the window object at the time the library is defined, just in case anyone redefines window in the global scope after jQuery is loaded.

  • including undefined as an argument (but not passing in a value) does the same thing for undefined, allowing variable munging and avoiding problems if the undefined variable is redefined (yup, Javascript allows this).

I believe in both cases this is supposed to speed up references to the variable, as it makes both global variables available in the function scope, which the interpreter will search before looking in the global scope. But I can't honestly imagine that the performance difference here is substantial - I think the biggest issue is the variable name munging, which makes for more compact code when minified.

这篇关于为什么这两个参数在jQuery源代码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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