Monkey patching

Monkey patching is a technique that uses the flexibility of the JavaScript to modify any function/method behavior.

Performing monkey patching is simple and it can be done by the following steps.

  1. Store the original function in a variable
  2. Now modify the function behavior
  3. Call the original function using apply.

This can be useful when you want to change the argument values of the function. For example, consider we have the following class.

 


        var math = function () {
            this.a = 1;
            this.b = 2;
        };

        math.prototype = {
            sum: function (a, b) {
                return a + b;
            }
        }

Now we can modify the method sum using the monkey patching technique as follows.


        var original = math.prototype.sum;   Step 1

        math.prototype.sum = function (a, b) {
            a = a * 2, b = b * 2;    Step 2

            return original.apply(this, [a, b]);    Step 3
        }

On executing the above method, the result will as follows.


       var obj = new math();

        obj.sum(1, 2); //return 6;
        //Expected: 3, Actual : 6 due to monkey patch

Happy Scripting… 🙂