是否有必要使用“typeof"?运算符来检查全局变量是否存在? [英] Is it necessary to use the "typeof" operator to check if a global variable exists?

查看:54
本文介绍了是否有必要使用“typeof"?运算符来检查全局变量是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编写的代码依赖于由同一页面引用的另一个脚本文件创建的对象时,我经常发现自己必须测试某个或其他全局变量的存在.

When I'm writing code that relies on objects created by another script file referenced from the same page I often find myself having to test for the existence of some global variable or another.

我希望这样做的逻辑习语如下:

I'd expect that the logical idiom to do that would be as follows:

if (window.myLibrary) myLibrary.someFunction();

然而,在对 stackoverflow 进行了一些研究之后,共识似乎是正确的习语是这样的:

However after some research on stackoverflow, the consensus seems to be that the correct idiom is this:

if (typeof myLibrary != "undefined") myLibrary.someFunction();

stackoverflow 上的几个答案中给出了这个习语,最突出的例子是这个:

This idiom is given in several answers on stackoverflow, the most prominent example being this one:

如何检查javascript中是否定义了变量

但是,我找不到任何解释为什么第二个版本更可取.对它的所有建议都采用只使用这个"的形式.有人可以解释一下为什么使用 typeof 运算符优于通过将对象作为 window 对象的属性进行引用来检查对象吗?

However, I can't find any explanation for why the second version is preferable. All the recommendations for it are in the form "just use this." Can someone please explain why using the typeof operator is superior to checking for the object by referencing it as a property of the window object?

推荐答案

我倾向于第一个例子,除非有一些真正令人信服的理由为什么有人可能会将库设置为true"或类似的东西.是的,如果您的代码在其他人的环境中运行(即,您正在构建像 JQuery 这样的公共 Javascript 框架),您可能希望通过类型检查尽可能安全,以确保有人不会滥用库.但在我看来,Javascript 中完美的类型安全并没有那么重要,以至于您的所有代码都非常冗长,有时甚至难以阅读.

I tend to go for the first example, unless there is some really compelling reason why someone might set the library to "true" or something similar. Yes, if your code is running in someone else's environment (ie, you're building a public Javascript framework like JQuery) you may want to be as safe as possible with the type-checking, to ensure someone isn't misusing the library. But in my view, perfect type safety in Javascript is not quite so important as to make all your code extremely verbose, and occasionally difficult to read.

我也喜欢链接问题的答案;你可以使用

I also liked an answer from the linked question; you can use

if ('myLibrary' in window)

我认为这只是偏好.澄清一下,即使 window.myLibrary 为false",它也会评估为 true,因此您基本上是在检查它是否已被定义.

I think that one's just preference. To clarify, that one will evaluate true even if window.myLibrary is 'false', so you'd basically be checking whether it was defined at all.

这篇关于是否有必要使用“typeof"?运算符来检查全局变量是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆