javascript - 在 Javascript 中覆盖 undefined 和 IIFE

标签 javascript

我一直在阅读“你不知道的 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 parameter undefined, but not passing any value for that argument, we can guarantee that the undefined identifier is in fact the undefined 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/

相关文章:

javascript - 解决回调中的 promise

javascript - 使用鼠标位置更改 D3 map 工具提示的类别

javascript - 如何将代码 thymeleaf 放在外部 javascript 文件中?

javascript - 如何找到位于给定 (X,Y) 位置的 DOM 节点? ( HitTest )

php - 通过 POST 将值提交到多个 PHP 文件

javascript - NodeJS 可以在网络上使用而不是在命令行上使用吗

javascript - GraphQL:从兄弟解析器访问另一个解析器/字段输出

javascript - 如何让 Firefox 控制台显示超过 200 个日志条目?

javascript - Node : display an image not in public folder

javascript - FileReader 异步读取方法是否会阻塞主线程?