Can someone give me an example of monkey patching regarding TypeScript & Angular2 and also an explanation ?
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.
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.
Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time.
Monkey patching is the first step towards meta-programming - writing code which writes code.
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With