overriding a global function in javascript

后端 未结 2 2416
温柔的废话
温柔的废话 2021-02-20 16:37

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;
         


        
相关标签:
2条回答
  • 2021-02-20 16:59

    Minor improvement to the Answer of Tim Down to mimic the original even more:

    window.oldSetTimeout = window.setTimeout;
    window.setTimeout = function(func, delay) {
        return window.oldSetTimeout(function() {
            try {
                func();
            }
            catch (exception) {
                //Do Error Handling
            }
        }, delay);
    };
    
    0 讨论(0)
  • 2021-02-20 17:01

    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.

    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.

    I'd suggest the following instead:

    window.oldSetTimeout = window.setTimeout;
    
    window.setTimeout = function(func, delay) {
        return window.oldSetTimeout(function() {
            try {
                func();
            }
            catch (exception) {
                //Do Error Handling
            }
        }, delay);
    };
    
    0 讨论(0)
提交回复
热议问题