3

ECMAScript 5 出现已经有一段时间了,并且在大多数现代浏览器(IE9、CH 19+、FF 4+)中都得到了很好的支持,“不可变未定义”也是如此。虽然我一直看到“未定义”像这样被传递:

(function ( ..., undefined ) {

})(...);

据我所知,Crockford 的 JSLint 工具并不喜欢它:

Expected an identifier and instead saw 'undefined' (a reserved word).

即使它没有被传递(函数调用没有参数)并且它实际上是一个标识符。我知道他的工具不是我们应该遵循的圣经,另一方面JSHint似乎并不关心它。

这在今天仍然被认为是最佳实践吗?它如何影响代码性能/安全性?考虑浏览器支持 >= IE9。

4

2 回答 2

3

这在今天仍然被认为是最佳实践吗?它如何影响代码性能/安全性?考虑浏览器支持 >= IE9。

就像undefined,Infinity是全局对象的不可写属性,而不是字面量 like null,因此它可以用作参数名称而不会引发错误。让我们考虑这样的函数

function example(Infinity) {
    return Infinity;
}

In example,Infinity不再是不可写的属性,而是像函数的任何其他参数一样,被初始化为undefined好像没有传递任何内容或以其他方式获取参数的值。这意味着在这个函数中你不能仅仅假设它Infinity意味着Infinity,因为它没有,但你可以假设它意味着undefined

So let's go back to the question of undefined. It will be initialised as undefined so the meaning will stay the same, however, it has now lost it's immutability within the function and therefore any typos assinging a values to undefined will have this error carried forward. Additionally, if a parameter is passed to the function the value will be different from the start.

Therefore to conclude, it does have an effect on security, as an undefined like this is no longer as "safe" because it has lost it's immutable status and can be changed.


It may be interesting to note that undefined is not actually a reserved word. If you require an undefined for compatibility, rather than adding it as a parameter name, I would suggest using a simple var undefined; at the top of the function or in the global namespace where you will find var undefined; undefined = 1; undefined; // undefined where it is immutable.

于 2013-01-28T17:22:05.197 回答
0

If you wanted to comply with jsLint, you could use another variable that is not a reserved word instead of undefined. The following complies with jsLint:

(function (window, document, undef) {
    'use strict';

}(window, document));

You would, however, need to remember to use your newly defined variable (in this case undef instead of undefined). The strict mode above was added to comply with jsLint. This is mostly used so that you know for certain that the variable you are testing to be undefined is actually undefined.

Note, that if you're running this example in the text area provided on the jsLint website, you may need to define window and document. I was receiving two errors until I did so.

var window = window; //global window object
var document = document; //global window object

However, I'm of the opinion that:

(function (..., undefined) {
    'use strict';

}(...));

is perfectly fine and more importantly, highly recommended.

There are cases where reserved words can be changed from their normal states. Such as setting undefined to true. Paul Irish discusses this briefly in his video: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

于 2013-01-28T17:26:22.893 回答