Let's say I define a component like this:
const myComponent = class MyComponent extends React.Component {}
and later I would like to add a constructor to the defined component like this:
myComponent.constructor = function(props) {
super(props)
this.state = { hello: 'world' }
}
Does anyone know if this is possible? If so, does anyone know what differences in implementation are required compared to the above? Thanks!
What is Monkey patching? A monkey patch is a way for a program to extend or modify supporting system software locally. Monkey patching replace methods / classes / attributes / functions at runtime.
Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.)
A monkey patch is a way to change, extend, or modify a library, plugin, or supporting system software locally. This means applying a monkey patch to a 3rd party library will not change the library itself but only the local copy of the library you have on your machine.
Etymology. Apparently from earlier guerilla patch (“code that sneakily changes other code”), understood as gorilla patch. A monkey patch was then a more carefully written instance of such a patch. Or simply derived from monkey (“to mess with”, verb).
You can not override constructor for es6 classes. You can do it with es5 classes, so it would work (and be brittle) with babel.
For other methods you would do
MyComponent.prototype.methodName = function() {}
This is IMO a missing feature as it would allow better dependency injection.
If TC39 should stumble onto this page I would love to have Reflect.setConstructor.
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