title: Append code to the end of an existing function
body: <p>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 I hate it).</p>
  
  <p>I wrote this function to add my code to the end of function foo:</p>
  
  <pre><code>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 ;
  }
  }
  </code></pre>
  
  <p>eg:</p>
  
  <pre><code>appendToFunction(foo,"bar();");
  </code></pre>
  
  <p>This strikes me as a terrible idea - but it works. Can somebody point me in a better (safer) direction please.</p>
  
  <p>EDIT: <code>foo</code> is not a specific function, but many functions that I wind up dealing with. They don't change dynamically in the page. But they may be changed (eg. form validation demands) from time to time.</p>
  
  <p><strong>Solution</strong>:
  I settled on a modified version of Adam's Answer. It's not perfect, but it's better than what I had:</p>
  
  <pre><code>var oldFoo = foo ;
  foo = function(){
          var result = oldFoo.apply(this, arguments);
          bar();
          return result ;
  }
  </code></pre>
  
  <p>NB. Watch out for some native functions in IE6/7 that don't have an <code>.apply()</code> method.</p>