传入undefined的目的是什么? [英] What is the purpose of passing-in undefined?

查看:163
本文介绍了传入undefined的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 jQuery 和相关的主题插件,如 jQuery.UI 传递 undefined 作为模块定义中使用的匿名函数的参数,如下所示:

I have noticed jQuery and related keynote plugins like jQuery.UI pass undefined as a parameter into anonymous functions used in their module definitions, like so:

(function($, undefined) { ... })(jQuery);

或者,我注意到jQuery和/或其他人推荐的其他插件不会将undefined传递为参数。

Alternatively, I have noticed other plugins recommended by jQuery and/or others do NOT pass undefined in as a parameter.

这可能是一个愚蠢的问题,但是......

This is probably a silly question, but...

不应该总是有空无论如何?为什么传递它?这里有其他目的或技巧吗?

Shouldn't it always be available anyway? Why pass it in? Is there some sort of other purpose or trick going on here?

推荐答案

这有两个原因:

1)如果 undefined 是函数作用域中的变量而不是全局对象属性,则minifiers可以将其减少为单个字母实现更好的压缩率。

1) If undefined is a variable in the function scope rather than a global object property, minifiers can reduce it to a single letter thus achieving a better compression rate.

2)在ES5 *之前, undefined 是全局对象的属性,没有写入-保护。所以它可能被覆盖,导致奇怪和意外的行为。你可以这样做:

2) Before ES5*, undefined was a property of the global object without write-protection. So it could be overwritten, resulting in strange and unexpected behavior. You could do something like this:

var test = 123;
undefined = 123;
if (test === undefined){
   // this will actually be true, since undefined now equals 123
}

通过函数参数 undefined (名称实际上无关紧要),你没有将参数传递给,你可以确保你有一个真正 undefined 的变量,这样你就可以对这个变量测试undefinedness。

By having an function argument undefined (the name actually does not matter) which you don't pass a parameter to, you could make sure you have a variable which really is undefined so you can test "undefinedness" against this variable.

顺便说一下。测试undefined的最安全的方法是: typeof(var)==='undefined'

Btw. the safest method to test for undefined is: typeof ( var ) === 'undefined'

(*)使用EcmaScript 5,全局属性未定义 NaN 无穷大变成了只读。因此,它在所有现代浏览器中得到普遍采用 - 当然除了IE 9之外 - 不再可能覆盖这些值。

(*) With EcmaScript 5, the global properties undefined, NaN and Infinity became readonly. So with its general adoption in all modern browsers - of course with the exception of IE 9 - overwriting those values was not possible anymore.

这篇关于传入undefined的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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