是否可以使用更短的辅助函数来代替 typeof something !== "undefined"?

Is it possible to use a shorter helper function instead of typeof something !== "undefined"?

这个很好用

var isRenderer = typeof process !== "undefined" && process.type === "renderer";

我不喜欢在我的代码中到处进行这些 typeof 检查,所以我尝试编写一个辅助函数。但是使用它会导致抛出引用错误

var isRenderer = !isUndefined(process) && process.type === "renderer";

function isUndefined(val) {
  return typeof val === "undefined";
}

我有两个问题:

I don't like having those typeof checks all over my code, so I tried writing a helper function. But using it causes a reference error to be thrown

如果您的函数出错,这告诉我们 process 是未声明的标识符,而不仅仅是值为 undefined 的 variable/parameter。您可以在未声明的标识符上使用 typeof,但无法读取其值。

不幸的是,您无法编写一个函数来执行您概述的操作。最接近的是:

var isRenderer = !isUndefined(typeof process) && process.type === "renderer";

function isUndefined(type) {
  return type === "undefined";
}

请注意,在您调用它的地方它仍然需要 typeof。但至少它避免了如果您在 "undefined" 中有错字(就像我经常做的那样)出现无声逻辑错误的机会。

最好的方法是查看您尝试使用未声明的标识符的原因并解决这些问题。但除非这样做,否则您将需要 typeof 检查。


如果 process 是声明的标识符,但它的值是 undefined,您的函数就可以工作。但在那种情况下,您很快就不需要它了,因为 optional chaining。这是现代 JavaScript 环境(Chrome v80+、Firefox v74+、Safari 13.1+)中 ES2020 规范中的一项新功能,如果您转译(例如, 和巴别塔)。那么您的声明将如下所示:

// ONLY WORKS IF `process` IS DECLARED
var isRenderer = process?.type === "renderer";

isRenderer 将是 false 如果 process 被声明但具有值 undefinednull,因为 process?.type 将评估为undefinedundefined === "renderer" 为假。

但同样,这在您遇到的情况下不起作用,因为 process 是未声明的标识符。

正如已经回答和评论的那样,您不能将未声明的变量传递给函数而不在尝试读取变量以将其作为参数传递时生成错误。

但是,如果 processnull,则在检查其属性之前简单地检查是否定义了 process 会失败。我通常使用并建议的解决方案是检查对象值,然后检查它不是 null:

if(typeof process === "object" && process && process.type === "renderer") 

通常更安全。