我一直在阅读“你不知道的 Js”系列并遇到了这个:
"Another application of this pattern addresses the (minor niche) concern that the default
undefined
identifier might have its value incorrectly overwritten, causing unexpected results. By naming a parameterundefined
, but not passing any value for that argument, we can guarantee that theundefined
identifier is in fact theundefined
value in a block of code: "
undefined = true; // setting a land-mine for other code! avoid!
(function IIFE(undefined) {
var a;
if (a === undefined) {
console.log("Undefined is safe here!");
}
})();
我不明白这里发生了什么。 undefined 是一种数据类型还是只是一个标识符,这段代码是如何工作的?
谢谢。
最佳答案
undefined
(标识符)是一个预定义的全局变量,其值令人困惑地是 undefined
,这是 Undefined 类型的唯一成员。 ( I kid you not .)
它曾经是undefined
(标识符)不是只读的,您可以分配给它。很久以前(2009 年,从 ES5 开始)就不再是这样了;这记录 undefined
,而不是 true
:
undefined = true;
console.log(undefined);
...但这就是该部分所描述的“利基问题”。
2018 年一个不同但真正的利基问题是您可以隐藏 undefined
标识符并赋予它任何您想要的值:
(function() {
var undefined = true;
console.log(undefined); // true
})();
因此,如果您的代码可能会出现在其他代码的中间,您可能会处理与全局标识符不同的 undefined
标识符。
因此,为了处理这种不太可能发生的情况,您可以编写隐藏 undefined
的代码,但使用正确的值,方法是使用将其声明为的 IIFE一个参数,然后不传入任何值;参数将接收的值将是实际值 undefined
:
(function() {
var undefined = true;
// ^---- a local variable that shadows (hides) the global
console.log(undefined); // true
(function(undefined) {
// ^---- a parameter that shadows (hides) the one above
console.log(undefined); // undefined
})(); // <== Notice we aren't passing any argument for the parameter here
})();
由于我们不传递参数,因此参数接收值 undefined
(无论undefined
标识符可能包含什么值任何给定范围)。
关于javascript - 在 Javascript 中覆盖 undefined 和 IIFE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50658144/