Adding code to a javascript function programmatically
You can make a function that calls your code, and then calls the function.
var old_someFunction = someFunction;
someFunction = function(){
alert('Hello');
old_someFunction();
alert('Goodbye');
}
I don't know if you can update the function, but depending on how it is referenced, you can make a new function in its place:
var the_old_function = someFunction;
someFunction = function () {
/* ..My new code... */
the_old_function();
/* ..More of my new code.. */
}
If someFunction
is globally available, then you can cache the function, create your own, and have yours call it.
So if this is the original...
someFunction = function() {
alert("done");
}
You'd do this...
someFunction = (function() {
var cached_function = someFunction;
return function() {
// your code
var result = cached_function.apply(this, arguments); // use .apply() to call it
// more of your code
return result;
};
})();
Here's the fiddle
Notice that I use .apply
to call the cached function. This lets me retain the expected value of this
, and pass whatever arguments were passed in as individual arguments irrespective of how many there were.
first store the actual function in a variable..
var oldFunction = someFunction;
then define your own:
someFunction = function(){
// do something before
oldFunction();
// do something after
};