这样做是在闭包内将undefined 重新分配给undefined。那是一个故障保险。因为其他代码可能会不小心做类似的事情
undefined = something;
console.log(undefined); // will output 'something'
这在javascript中是有效的(如果使用的JS引擎没有实现ECMAScript 5规范,在ECMAScript 5规范中undefined不是non-writable,MDN DOC),
引用自 MDN New_in_JavaScript 1.8.5 (ECMA 5) 页面
对全局对象的更改
全局对象设为只读
NaN、Infinity 和 undefined 全局
根据 ECMAScript 5 规范,对象已只读。
来自 Guthub 的 ES5 Annotated Spec
ES5 spec Sectionx15.1.1.3
15.1.1.3 未定义
undefined 的值是 undefined(见 8.1)。
此属性具有属性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }。
即使global undefined 不可写你也可以有一个名为undefined 的局部变量并且可能会弄乱你的代码(主要是与undefined 比较)。 但这是你的责任。你可以有类似的代码
(function(){
console.log('Second Case: ');
var undefined = 'Something';
console.log(undefined); // Will log `something`
var a ; // a is undefined
console.log(a === undefined); // false, as undefined is changed
// you might expect a === undefined will return true, but as
// `undefined` is changed it will return false.
console.log(a); // undefined
})();
演示: http://jsfiddle.net/joycse06/V4DKN/
但是,如果undefined 是可写的,那么上面的赋值可能会妨碍在该代码行之后使用undefined 生成的许多comparison,因为undefined 不再是undefined。它现在有一些价值。
所以当他们像这样调用匿名函数时
( window ) // one argument only
并接收
( window, undefined) // only window is passed when calling the function
// Second argument is not passed means it's undefined
// so undefined is restored to undefined inside that function
// and no global accidental assignments can hamper jQuery's
// code using 'undefined' now
这意味着在闭包内部undefined 被恢复为undefined,因为它没有被传递任何值,从而确保在该匿名函数中使用undefined。
关于这个http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/的一篇很好的详细文章
我引用上面文章链接中的一些内容来说明问题
什么是未定义的?
在 JavaScript 中有未定义(类型)、未定义(值)和未定义(变量)。
未定义(类型)是内置的 JavaScript 类型。
undefined (value) 是一个原始类型,是 Undefined 类型的唯一值。
任何未分配值的属性都假定为未定义的值。 (ECMA 4.3.9
和 4.3.10)。
没有 return 语句的函数,或带有空 return 语句的函数返回 undefined。未提供的函数参数的值未定义。
var a;
typeof a; //"undefined"
window.b;
typeof window.b; //"undefined"
var c = (function() {})();
typeof c; //"undefined"
var d = (function(e) {return e})();
typeof d; //"undefined"
undefined (variable) 是一个初始值为 undefined (value) 的全局属性,由于它是一个全局属性,我们也可以将其作为变量访问。为了保持一致性,在本文中我总是将其称为变量。
typeof undefined; //"undefined"
var f = 2;
f = undefined; //re-assigning to undefined (variable)
typeof f; //"undefined"
从 ECMA 3 开始,它的值可以重新分配:
undefined = "washing machine"; //assign a string to undefined (variable)
typeof undefined //"string"
f = undefined;
typeof f; //"string"
f; //"washing machine"
不用说,将值重新分配给未定义的变量是非常糟糕的做法,实际上 ECMA 5 不允许这样做。