覆盖javascript中的全局函数 [英] overriding a global function in javascript

查看:109
本文介绍了覆盖javascript中的全局函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将自己的错误处理添加到JavaScript setTimeout函数中。以下代码在chrome中工作正常:

I am trying to add my own error handling to the JavaScript setTimeout function. The following code works fine in chrome:

var oldSetTimeout = window.setTimeout;
window.setTimeout = function setTimeout(func, delay) {
    var args = Array.prototype.slice.call(arguments, 0);
    args[0] = function timeoutFunction() {
        var timeoutArgs = Array.prototype.slice.call(arguments, 0);
        try {
            func.apply(this,timeoutArgs);
        }
        catch (exception) {
            //Do Error Handling
        }
    }
    return oldSetTimeout.apply(this, args);
}

但是在IE7中它变成了一个递归函数。由于某种原因, oldSetTimeout 被设置为新函数。

But in IE7 it turns into a recursive function. For some reason oldSetTimeout gets set to the new function.

有什么建议吗?




旁注:是的,我需要这样做这条路。我正在使用一堆第三方库,所有这些都不能很好地处理setTimeout,所以我不能只是将调用更改为setTimeout。


side note: Yes, I need to do it this way. I am using a pile of 3rd party libraries all of which don't deal with setTimeout well, so I can't just change the calls to setTimeout.

推荐答案

这是因为你正在使用命名函数表达式,它们在IE中被错误地实现。删除功能名称将解决紧急问题。请参阅 kangax 关于这个主题的优秀文章。但是,还有一个问题不容易解决。

This is because you're using named function expressions, which are incorrectly implemented in IE. Removing the function names will fix the immediate problem. See kangax's excellent article on this subject. However, there's another problem that isn't so easily fixed.

通常,尝试覆盖主机对象的属性(例如<$ c)并不是一个好主意。 $ c> window , document 或任何DOM元素),因为无法保证环境允许它。主机对象不受与本机对象相同的规则的约束,实质上可以做他们喜欢的事情。也不能保证主机方法是 Function 对象,因此 oldSetTimeout 可能没有 apply()方法。在IE中就是这种情况,因此调用 oldSetTimeout.apply(this,args); 将无效。

In general, it's not a good idea to attempt to override properties of host objects (such as window, document or any DOM element), because there's no guarantee the environment will allow it. Host objects are not bound by the same rules as native objects and in essence can do what they like. There's also no guarantee that a host method will be a Function object, and hence oldSetTimeout may not have always have an apply() method. This is the case in IE, so the call to oldSetTimeout.apply(this, args); will not work.

我建议改为:

window.oldSetTimeout = window.setTimeout;

window.setTimeout = function(func, delay) {
    return window.oldSetTimeout(function() {
        try {
            func();
        }
        catch (exception) {
            //Do Error Handling
        }
    }, delay);
};

这篇关于覆盖javascript中的全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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