2012-11-01 95 views
1

我试图重写clearTimeout功能,在除了IE以外的浏览器上运行完全正常(在IE8测试)为什么在IE8上b/w window.clearTimeout和clearTimeout有什么不同?

clearTimeout = function(){}; 

IE8提供了以下错误:

Object doesn't support this action 

但是,当我这样做,

window.clearTimeout = function(){}; 

它可以很好的覆盖clearTimeout。这是为什么?

此外,无处不在我的代码我打电话clearTimeout而不是直接为window.clearTimeout。所以,即使我重写clearTimeout(通过第二种方式),本机clearTimeout被调用,而不是重写的clearTimeout。什么可以解决这个问题?

+2

为什么你重写默认行为? –

+0

我正在写QUnit测试用例,其中我试图跟踪clearTimeout是否被调用,或者没有使用特定参数。 – hariom

+2

窗口对象是一个主机对象,clearTimeout是一个主机方法。他们不必遵守ECMA-262,并且可以做他们喜欢(几乎)的事情。 – RobG

回答

0

In IE, initially, the property setTimeout exists on the prototype of window, not on window itself. So, when you ask for window.setTimeout, it actually traverses one step on the prototype chain to resolve the reference. Similarly, when you ask for setTimeout, it traverses down the scope chain, then to window, then down the prototype chain to resolve the reference.

I suspect that IE has a built-in optimization where it automatically caches the resolution of implied globals that are discovered all the way down on the prototype of the global object. It would have good reason to do so, as these are commonly requested references, and traversing that chain is costly. However, it must be setting this reference as read-only, since it's just a caching optimization. This has the unfortunate side-effect of causing an exception to be thrown when attempting to assign to the reference by using it as an lvalue.

来源:http://www.adequatelygood.com/2011/4/Replacing-setTimeout-Globally

+0

我有一个快速尝试在IE8中设置window.constructor.prototype.setTimeout,但似乎并没有做任何事情 - 可能是因为窗口是DispHTMLWindow2类型的本机对象。 – robocat

相关问题