2012-11-01 81 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

相關問題