Search code examples
javascriptmonkeypatching

How to modify (monkey-patching) third-party function at specific line


I'm wonder is it possible to modify third-party function (like monkey-patching [wiki], [nice article]) in a way to add some few lines in the middle of those functions?

Example of what I want:

Third-party (patching target):

var obj = {
  sum: function (a) {
    var b = 1;
    //Here I want to add a line:
    // b = 2
    return a + b;
  }
};

N.B.: I know that we can execute custom functions before and after a original function call, but I want to execute custom code in the middle of the original function's body.

UPD: I'll share my thoughts below as an answer, but it's ugly so I want to find any other ways.


Solution

  • This is a little bit ugly way to do that. I didn't test it well, but it's should work:

        // Split function into array of strings
        var arr = obj.sum.toString().split('\n');
        // Insert our expression (b = 2) at "line 2"
        arr.splice(2, 0, "b = 2");
        // Remove first line: "function (a) {" (to be honest we should first parse and remember args)
        arr.splice(0, 1)
        //Remove last line: "}"
        arr.splice(arr.length-1, 1)
        // Create a string with our function
        var str  = arr.join("\n")
        //Create function with new Function()
        var newFunc = new Function("a", str); //a -is our argument for "sum" func
        obj.sum = newFunc;