Extending a JavaScript Function

7, Aug 2012

Contents

I'm currently working on writing a modular plugin system for an application at work, and I had the need of being able to tap into a core function of the application, and have it do some additional work once it was finished. Since the use for this requires not modifying a core function, adding a call back is not acceptable. Additionally, it has to be able to be extended multiple times, since multiple plugins may be active at once.

Base Function

Firstly we need to have the functionality that we're going to be extending, for these purposes, I'm just going to make a very simple demonstration function:

function adder(param1, param2) {
    console.log("In base Function");
    return param1 + param2
}

Once that's written, let's make our wrapper for it.

Wrapper/Extension Function

// Create an anonymous function to wrap everything in. This gets called immediately
// on script load.
(function() {
    // Store a copy of the original function that will be extended so that we can call
    // it in our new function
    var old_adder = adder;

    // Create a new function with the same name as the function we're extending.
    // This overrides the existing one, so that all calls to that function call this
    // new one instead
    adder = function() {

        // Now, inside our extended function, we have the opportunity to take
        // actions before calling the original:
        console.log("Before");

        // Call the original function, and pass the arguments to it, storing the return
        // value in a new variable
        var result = old_adder.apply(this, arguments);

        // Additional work can be done after the original function has run as well:
        console.log("After");

        // Return the result of the original function, or return something different
        // thanks to further processing that you may have done, to the original
        // caller of the base function.
        return result;
    }
})();

That's a Wrap!

That's all there is to it. This is a really neat functionality, as it allows for you to easily drop hooks in to your code base in a very modular fashion. There's nothing special at all that needs to be done to use the extended function, simply call adder in the regular fashion:

adder(5, 2) // Returns 7

Comments

This space intentionally left blank.

Have Something to Say?

Questions? Comments? Concerns? Let me know what you’re thinking.

  • You can use Markdown formatting here.