简体   繁体   English

Javascript 检查 window 是否未定义

[英]Javascript checking if window is undefined

I was writing a check to see if my code is running on the browser and I first tried the following 2 approaches:我正在编写检查以查看我的代码是否在浏览器上运行,我首先尝试了以下两种方法:

if (window) {
    // do browser stuff
}


if (window !== undefined) {
    // do browser stuff
}

When I try using this code, I get an error saying window is not defined.当我尝试使用此代码时,我收到一条错误消息,指出window未定义。 However, when I try the following approach it works:但是,当我尝试以下方法时,它起作用了:

if (typeof window !== 'undefined') {
    // do browser stuff
}

Why do the first 2 if statements throw an error but the third doesn't?为什么前两个 if 语句会抛出错误而第三个不会?

So the identity checks window !== undefined and window throw an error because window was not defined.因此身份检查window !== undefinedwindow抛出错误,因为 window 未定义。 That's exactly what the error is telling you when you try it in the console:这正是您在控制台中尝试时错误告诉您的内容:

VM49:1 Uncaught ReferenceError: iDoNotExist is not defined VM49:1 Uncaught ReferenceError: iDoNotExist 未定义

I think the misconception that this should work comes from how the identity check is usually used.我认为这应该起作用的误解来自身份检查的通常使用方式。 In functions we often perform this kind of check on the input parameter.在函数中,我们经常对输入参数执行这种检查。

const myFunction = (inputParam) => {
   if (inputParam){
      console.log(inputParam)
   } else {
      console.log("invalid parameter")
   }
}

myFunction("hello")
// 'hello'

myFunction()
// 'undefined'

myFunction(null)
// 'undefined'

myFunction(undefined)
// 'undefined'

The typeof -operator on the other hand returns the type of its operand as a string.另一方面, typeof运算符将其操作数的类型作为字符串返回。 Since undefined is one of JavaScripts types the expression does not throw an error and returns 'undefined' instead.由于 undefined 是 JavaScript 类型之一,因此表达式不会抛出错误并返回“undefined”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM