Search code examples
javascripttypescriptangular

What is monkey patching regarding TypeScript ?


Can someone give me an example of monkey patching regarding TypeScript & Angular2 and also an explanation ?


Solution

  • Because JavaScript is highly dynamic you can replace a member function (and related functionality) on any object with a new one. It allows you to modify the behaviour of a piece of code without altering the original code.

    Here is a simple example in TypeScript:

    // original code, assume its in some library
    interface Foo {
        a:number,
        b():number
    }
    var foo:Foo = {a:123,b:function(){return this.a}} 
    
    // Monkey patch the function b with a new one
    // Allows you to change the behaviour of foo without changing the original code
    foo.b = function(){return 456}
    

    More : Monkey patching is not just interception

    When you replace the function but retain the original behaviour, it is function interception. Yes you use monkey patching for function interception (replace the function) but calling the original function is not a requirement for monkey patching.

    Also from Wikipedia : https://en.wikipedia.org/wiki/Monkey_patch an application that clearly replaces original behaviour:

    Replace methods / classes / attributes / functions at runtime, e.g. to stub out a function during testing;

    Finally, just because you can call the original doesn't mean you have to call the original when monkey patching.