gpt4 book ai didi

javascript - Internet Explorer 7/8 和窗口函数是空对象

转载 作者:搜寻专家 更新时间:2023-11-01 04:52:37 26 4
gpt4 key购买 nike

在 Internet Explorer 8 中(也适用于 IE9 的 IE7/8 模式)以下代码警告 objectundefined 而不是预期的 function和类似 function() { [native code] } 的东西。

alert("typeof window.setTimeout = " + typeof window.setTimeout);  // object
alert("window.setTimeout.apply = " + window.setTimeout.apply ); // undefined

试一试:http://jsfiddle.net/BsvZw/5/

为什么会这样?获取实际 setTimeout 的解决方法是什么?

更新

我正在尝试围绕 setTimeout 创建一个包装器:

var _oldSetTimeout = window.setTimeout;
window.setTimeout = function ()
{
// ...

return _oldSetTimeout.apply(this, arguments); // this is place where IE 7/8 says 'Object doesn't support this property or method'
// and _oldSetTimeout looks like an empty object
};

最佳答案

Why is this happening?

基本上,因为 IE 讨厌 Web 开发人员并且正在惹你。

更严重的是,浏览器实现提供的不属于核心 Javascript 语言的内容可能被归类为 host objects .当谈到宿主对象时,所有赌注都被取消了,它们基本上可以做任何他们想做的事[1],而无需遵守通常的 Javascript 语义。

What would be a workaround to get the actual setTimeout?

我知道它真的很难看,但你可以做一个 if-else-if 链直到预定义数量的参数。在 setTimeout 的情况下,这应该不是什么大问题,因为您不应该需要超过 2 个或 3 个参数。

var _oldSetTimeout = window.setTimeout;
window.setTimeout = function (a1, a2, a3)
{
switch(arguments.length){
case 0: return _oldSetTimeout();
case 1: return _oldSetTimeout(a1);
case 2: return _oldSetTimeout(a1, a2);
default: return _oldSetTimeout(a1, a2, a3);
}
};

虽然这是一个非常丑陋的解决方案,但有时它是唯一的方法。例如,也无法使用可变参数调用构造函数。


[1] 为了让您了解宿主对象有多邪恶,前几天我不得不对 DOM 节点/文档中的 XPath 方法进行特征检测。我不得不使用 if("selectNodes"in node) 而不是通常的 if(node.selectNodes) 测试,因为节点是 IE 中的主机对象并且只访问 selectNodes属性实际上会调用它,给我一个“参数数量不正确”的异常!

关于javascript - Internet Explorer 7/8 和窗口函数是空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11619826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com