Append code to the end of an existing function

ColBeseder picture ColBeseder · Jun 27, 2012 · Viewed 14.4k times · Source

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).

I wrote this function to add my code to the end of function foo:

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 ;
}
}

eg:

appendToFunction(foo,"bar();");

This strikes me as a terrible idea - but it works. Can somebody point me in a better (safer) direction please.

EDIT: foo 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.

Solution: I settled on a modified version of Adam's Answer. It's not perfect, but it's better than what I had:

var oldFoo = foo ;
foo = function(){
        var result = oldFoo.apply(this, arguments);
        bar();
        return result ;
}

NB. Watch out for some native functions in IE6/7 that don't have an .apply() method.

Answer

Adam Heath picture Adam Heath · Jun 27, 2012

You can just override foo with a custom function that calls the original.

E.g.

var old_foo = foo;
foo = function() {
  old_foo();
  bar();
}

You should also pass any arguments foo takes into it via your replacement function.