`typeof (...) === 'undefined'` 和 `(...) === void 0` 有什么区别? [重复]

问题描述 投票:0回答:1

在做一些打字稿时,我遇到了我以前在 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'
吗?如果不是,哪一个更好,为什么?

谢谢

javascript
1个回答
3
投票

有差异。

如果您正在检查全局变量

x
, 然后
typeof x === 'undefined'
将返回
true
x === void 0
抛出
ReferenceError

您需要使用
window.x === void 0
才能获得
true
。 然而在这种情况下,它知道
x
至少会被设置为
undefined
,因为它是一个函数参数,所以错误永远不会成为问题。

我认为为了可读性,我更愿意使用

typeof x === 'undefined'

© www.soinside.com 2019 - 2024. All rights reserved.