JavaScript debugging tip: Monkey Patching

Posted on 2/13/2015 @ 12:24 PM in #Vanilla .NET by | Feedback | 1969 views

Frequently we inherit code, especially in JavaScript, code that we cannot change, or is so deep down in a basement of a skyscraper that we are afraid to change. But damn we’d like to know what is going on, and how it gets called etc. Monkey patching is a technique that lets you easily change the definition of that function, on the fly!

Where would this be useful? Simple – where you want to change the behavior or definition of any JavaScript function , entirely, without, actually changing the function in code. So the rest of the dependencies don’t know what is going in. A simple example could be to simply console.log the parameters for debugging purposes. Here is how you do it.

Check this function out,

   1:  function add(a,b) {
   2:      return a + b;
   3:  }

Easy huh? The function adds! But lets say I want to completely change what this function does, without affecting the source code! I want to affect it only for my scope! The change I would like to make is, I want to console.log the arguments. Here is how I’d do it,

Step #1 – save the function in a variable,

   1:  var originalAdd = add;

Step #2 – change the definition of the function, while calling the original function, like this -

   1:  add = function() {
   2:      console.log(arguments);
   3:      return originalAdd.apply(this, arguments);
   4:  }

Great! Now call the function add again – it behaves just like before (because I am calling originalAdd), but in addition it logs out the parameters!

Sound off but keep it civil:

Older comments..