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

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.

Leave a Comment