Extending JavaScript Functions

This is a pattern you can use to extend JavaScript Functions, including native functions.

For example, we’ll extend the join() function of the Array type and add some logging before passing control back to the native join() function.

Array.prototype.join = (function(_super) {

    // return our new `join()` function
    return function() {
        console.log("Hey, you called join!");
        return _super.apply(this, arguments);
    };         // Pass control back to the original join()
               // by using .apply on `_super`

// Pass the original function into our
// immediately invoked function as `_super`
// which remains available to our new
// function thanks to JavaScript closures.

Jonathan D. Johnson

Loving my wife, my sons, and my work. Building codeship by day and packtracker by night, otherwise you can probably find me outside 🧗🏻‍♂️🏕