Search code examples
javascriptmethodsinvokemonkeypatching

Javascript Pocket Reference, p. 121: How is this "monkey-patching" method supposed to work?


As an illustration of the concept of apply(), the book Javascript Pocket Reference, O'Reilly, 3rd Edition 2012 presents this code sample:

// Replace the method named m of the object o with a
// version that logs messages before and after invoking
// the original method.
function trace(o, m) {
    var original = o[m]; // Remember original method.
    o[m] = function() {
        // Now define the new method.
        console.log(new Date(), "Entering:", m); // Log
        // Invoke the original method
        var result = original.apply(this, arguments);
        console.log(new Date(), "Exiting:", m); // Log
        // Return the result of the original method
        return result;
    };
}

I understand what this trace method is supposed to do (take an object and wrap the method to log the the start and end of execution time.)

I just don't understand how is this supposed to be able to do that. It does not return the new o[m] method and it also does not invoke it.

If I have

var obj = {
    double: function(num) {
        return 2 * num;
    }
}

how do I invoke trace to see the logs?


Solution

  • It's replacing a method named m in an object. m is really just a key in the object hash pointing to a function, and trace replaces that with another function that wraps the original.

    In your case, you'd invoke it like this:

    trace(obj, 'double');
    

    And you'd call it like this:

    obj.double(2);