Append code to the end of an existing function

后端 未结 5 2038
别那么骄傲
别那么骄傲 2021-02-04 03:17

I need to trigger function bar() whenever function foo() fires. I have no control over function foo or whether it will change in the future. I have this situation regularly (and

5条回答
  •  自闭症患者
    2021-02-04 04:07

    You could do something like this: THE DEMO.

    function foo() {
     console.log('foo');
    }
    
    function appendToFunction(fn, callback) {
      window[fn] = (function(fn){
        return function() {
          fn();
          callback();
        }
     }(window[fn]));
    }
    
    appendToFunction('foo', function(){console.log('appended!')});
    
    foo();
    

提交回复
热议问题