Append code to the end of an existing function

后端 未结 5 1981
别那么骄傲
别那么骄傲 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:10

    function extend(fn,code){
      return function(){
        fn.apply(fn,arguments)
        code.apply(fn,argumnets)
      }
    }
    

    and use it like this:

    function appendToFunction(fn,code){ 
        if(typeof fn == 'function'){
            var fnCode = fn.toString() ;
            fnCode = fnCode.replace(/\}$/,code+"\n}") ;
            window.eval(fnCode);                    // Global scope
            return true ;
        }
        else{
            return false ;
        }
    }
    
    appendToFunction = extend(appendToFunction,function(){/*some code*/});
    

    this will give you the same "this" in both functions

提交回复
热议问题