问题
This works fine
var isRenderer = typeof process !== "undefined" && process.type === "renderer";
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";
}
I have two questions:
- Why does the helper function I wrote not work?
- Is it possible to write a helper function to replace the typeof checks?
回答1:
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
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";
}
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).
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.
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
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.
But again, that won't work in the situation you have, since process
is an undeclared identifier.
回答2:
As has been answered and commented, you can't pass an undeclared variable to a function without an error being generated when trying to read the variable to pass it as an argument.
However, simply checking that process
is defined before checking its properties fails if process
is null
. The solution I normally use and would suggest is to check for an object value and then check it's not null
:
if(typeof process === "object" && process && process.type === "renderer")
is generally safer.
来源:https://stackoverflow.com/questions/62320045/is-it-possible-to-use-a-shorter-helper-function-instead-of-typeof-something