为什么这两个参数会出现在jQuery源码中呢?

发布于 2024-12-12 04:59:54 字数 290 浏览 0 评论 0原文

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

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

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

既然window是全局变量,为什么还需要传入呢?传入全局参数并在闭包内以相同名称访问它的目的是什么?

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

又爬满兰若 2024-12-19 04:59:55

我很确定这个问题已经得到了回答,但是:

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

  • undefined 包含为参数(但不传入值)对于 undefined 具有相同的作用,允许变量修改并避免在 undefined< 时出现问题/code> 变量被重新定义(是的,Javascript 允许这样做)。

我相信在这两种情况下,这都应该加快对变量的引用,因为它使两个全局变量在函数作用域中可用,解释器在查看全局作用域之前将对其进行搜索。但老实说,我无法想象这里的性能差异很大 - 我认为最大的问题是变量名修改,这使得缩小时的代码更加紧凑。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文