Adding code to a javascript function programmatically
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; };})();
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};
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');}