Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is monkey patching regarding TypeScript ?

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

like image 309
Ray Kim Avatar asked Jan 19 '16 22:01

Ray Kim


People also ask

What is monkey patching in Javascript?

Monkey patching is more a way for debugging, experiencing, patching, or hacking existing code than rather a long-term solution for a code base, even if it could be used as a natural solution in a few specific cases.

What is monkey patching in angular?

Monkey patching is a fancy term to describe decorators. A decorator in its simplest form is a wrapper function that takes in another function and “decorates” it. It's most commonly used as a technique to override or extend the behavior of built-in methods without altering the original source code.

What does monkey Patch_all () do?

Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time.

Is monkey patching metaprogramming?

Monkey patching is the first step towards meta-programming - writing code which writes code.


1 Answers

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.

  • The python answer What is monkey patching? (replacement / overriding only)

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.

like image 88
basarat Avatar answered Oct 14 '22 14:10

basarat