Javascript 类型未定义和 void 之间的区别

Javascript difference between typeof undefined and void?

本文关键字:之间 区别 void 类型 未定义 Javascript      更新时间:2023-09-26

在做一些打字稿时,我遇到了这个我以前在javascript中从未见过的东西。

constructor(public x: number = 0, public y: string = "none"){
        this.color = "red";
    }

该部分正在编译为:

    if (x === void 0) { x = 0; }
    if (y === void 0) { y = "none"; }

但不应该是typeof x === 'undefined'吗? 如果不是,哪一个更好,为什么?

谢谢

有差异。

如果要检查全局变量 x ,然后typeof x === 'undefined'会返回truex === void 0抛出ReferenceError.
您需要使用window.x === void 0才能获得true。 但是在这种情况下,它知道x至少会设置为 undefined,因为它是一个函数参数,因此错误永远不会成为问题。

我认为为了可读性,我更喜欢使用typeof x === 'undefined'.