我一直在阅读“你不懂Js”系列,并发现了这一点:
“此模式的另一个应用解决了默认值的(次要利基)问题undefined
标识符的值可能会被错误地覆盖,从而导致意外结果。通过命名参数undefined
,但不为该参数传递任何值,我们可以保证undefined
标识符实际上是undefined
代码块中的值:“
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 是一种数据类型还是只是一个标识符?这段代码是如何工作的?
Thanks.
undefined
(标识符)是一个预定义的全局变量,其值令人困惑的是,undefined
,它是 Undefined 类型的唯一成员。 (我没有骗你.)
It used成为那个undefined
(标识符)不是只读的,您可以分配给它。这在很久以前就不再成立了(2009 年,截至 ES5);这个日志undefined
, not true
:
undefined = true;
console.log(undefined);
...但这就是该部分描述的“利基问题”。
A 不同的,但 2018 年真正的、小众的担忧是,你可以shadow the undefined
标识符并给它任何你想要的值:
(function() {
var undefined = true;
console.log(undefined); // true
})();
因此,如果您的代码可能被放置在其他代码中间,那么您可能正在处理不同的代码undefined
标识符比全局标识符。
So,为了处理这种极不可能发生的情况,您可以编写隐藏的代码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
})();
由于我们不传递参数,因此参数接收value undefined
(无论值是多少undefined
标识符可能保存在任何给定范围内)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)