I'd like to monkey patch the constructor for this 'Controller' object. But how do I monkey patch the constructor function so I can still call the original? This is what I've tried.
// original
function Controller() {
this._tag = 'div';
}
Controller.prototype.tag = function() {
console.log(this._tag);
}
var c = new Controller();
c.tag(); // -> 'div', as expected
// patch attempt
var original = Controller;
Controller = function() {
original.apply(this);
this._tag = 'patched'; // patch
}
var c = new Controller();
c.tag(); // no method tag, prototype appears wiped...
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.
//Constructor function User (name, age) { this.name = name; this. age = age; } var user1 = new User('Bob', 25); var user2 = new User('Alice', 27); In the above example, arguments are passed to the constructor during object creation. This allows each object to have different property values.
Object() constructor Its behavior depends on the input's type. If the value is null or undefined , it creates and returns an empty object. Otherwise, it returns an object of a Type that corresponds to the given value. If the value is an object already, it returns the value.
You seem to want to do something like:
Constructor.prototype.oldTag = Constructor.prototype.tag;
Constructor.prototype.tag = function() {/* whatever */};
Now all instances get the new tag method and you can still call oldTag if you want (or put it back).
Or perhaps you want to do something like:
var oldConstructor = Constructor;
var Constructor = function () { /* new constructor */ };
Constructor.prototype = oldConstructor.prototype;
So now you have a new constructor with all the old methods. Or do both the above. Just use plain English to say what you want to do.
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