javascript - javascript中是否有一种简单的方法来测试IE8中的 “null or not an object”错误

标签 javascript error-handling internet-explorer-8

长期以来,我一直信任许多代码示例,这些示例显示了所谓的“安全”检测不可用的对象或对象属性,下面是两个快速的示例:

var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
或者也许要确保有可用的服务或过程,以便我采取替代措施,例如...
 if (!window.event) // do something else
 if (!window.XMLHttpRequest) // do something else
我没有进行以上任何测试,但是从这里的stackoverflow答案中选择了它们,通常是从高评价的答案中选择。但是,当我在IE8上运行带有此构造的代码时,脚本将停止,调试器将吐出诸如...的错误。
'window.event' is null or not an object 
'window.XMLHttpRequest' is null or not an object 
'window.innerWidth' is null or not an object
当然,它们不是“警告”。它们是使一切停止的错误。因此,我猜没有容易的方法来测试IE8中的此类对象或对象属性吗?我想我可以将try/catch块放在每个对象的周围这行代码可能会引起“null or not a object”(空对象或非对象)投诉,但这肯定会使我的库变得更大,甚至更慢!而且像这样的条件编译构造似乎效果不佳。 。
<!--[if gte IE 9 | !IE ]>-->
 // do something only if !IE or IE > 8
<!--<![endif]>-->
// resume normal inclusion? usually not reliably!
因此,在我给出的导致错误的示例中,我该怎么做才能使不支持对象的浏览器仅使用普通的javascript就能使代码更安全?

最佳答案

好吧,由于对“in”运算符的支持可以一直追溯到IE 5.5(至少根据此MDN引用文章:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in),因此您可以尝试执行以下操作:

if ('event' in window || 'innerWidth' in window || 'XMLHttpRequest' in window) {

    // Do stuff...

}

关于javascript - javascript中是否有一种简单的方法来测试IE8中的 “null or not an object”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65152414/

相关文章:

javascript - 如何使用 JavaScript 替换该字符串中的数字?

javascript - Tablesorter addParser 用于日期,如 "aa, dd.mm.yyyy"

python - 您如何顺序处理可能引发错误的多行代码?

ruby - module_eval/class_eval/instance_eval 如何统计行号

javascript - IE强制兼容模式

internet-explorer-8 - Selenium + IE8 : force IE8 compatibility view

css - IE 8 中的粘性页脚仅在直接访问页面后才与内容重叠

javascript - 在 Jquery.load 调用 JavaScript 函数

javascript - 限制输入数字小数点前后的数字

javascript - 将 “then.catch”嵌套在JavaScript的另一个 “then”中,可以期望什么结果?