问题描述
这很好用
var isRenderer = typeof process !== "undefined" && process.type === "renderer";
我不喜欢在我的代码中进行这些 typeof 检查,所以我尝试编写一个辅助函数.但是使用它会导致抛出引用错误
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
var isRenderer = !isUndefined(process) && process.type === "renderer";
function isUndefined(val) {
return typeof val === "undefined";
}
我有两个问题:
- 为什么我编写的辅助函数不起作用?
- 是否可以编写一个辅助函数来替换 typeof 检查?
推荐答案
如果您的函数出现错误,这告诉我们process
是一个未声明的标识符,而不仅仅是一个值为undefined
的变量/参数.您可以在未声明的标识符上使用 typeof
,但无法读取其值.
If you got an error with your function, that tells us that process
is an undeclared identifier, not just a variable/parameter whose value is undefined
. You can use typeof
on an undeclared identifier, but you can't read its value.
不幸的是,您无法编写函数来执行您概述的操作.离你最近的地方是:
Unfortunately, you can't write a function to do what you've outlined. The closest you can come is:
var isRenderer = !isUndefined(typeof process) && process.type === "renderer";
function isUndefined(type) {
return type === "undefined";
}
请注意,在您调用它的地方仍然需要 typeof
.但至少它避免了在 "undefined"
中有错别字时出现无声逻辑错误的机会(我经常这样做).
Note that it still needs typeof
at the point where you're calling it. But at least it avoids the opportunity of a silent logic error if you had a typo in "undefined"
(as I often do).
最好的方法是查看您尝试使用未声明标识符的原因并解决这些问题.但除非这样做,否则您将需要 typeof
检查.
The best course is to look at the reasons you would be trying to use an undeclared identifier and address those. But barring doing that, you'll need the typeof
check.
如果 process
是一个已声明的标识符,但它的值为 undefined
,那么您的函数就会起作用.但在这种情况下,您很快就不需要它了,因为 可选链.这是 ES2020 规范中的一项新功能,适用于现代 JavaScript 环境(Chrome v80+、Firefox v74+、Safari 13.1+),如果您进行转换(例如,使用 Babel),则可以在较旧的 JavaScript 环境中使用.那么您的语句将如下所示:
If process
were a declared identifier but it had the value undefined
, your function would have worked. But in that scenario, you soon wouldn't need it because of optional chaining. That's a new feature in the ES2020 specification that's in modern JavaScript environments (Chrome v80+, Firefox v74+, Safari 13.1+) and can be used with older JavaScript environments if you transpile (for instance, with Babel). Then your statement would look like this:
// ONLY WORKS IF `process` IS DECLARED
var isRenderer = process?.type === "renderer";
isRenderer
将是 false
如果 process
已声明但值为 undefined
或 null
,因为 process?.type
将评估为 undefined
,而 undefined === "renderer"
为假.
isRenderer
would be false
if process
were declared but had the value undefined
or null
, because process?.type
would evaluate to undefined
, and undefined === "renderer"
is false.
但同样,这在您的情况下不起作用,因为 process
是未声明的标识符.
But again, that won't work in the situation you have, since process
is an undeclared identifier.
这篇关于是否可以使用更短的辅助函数而不是 typeof something !== "undefined"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!