Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I monkey patch an object's constructor function?

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...
like image 307
Dane O'Connor Avatar asked Dec 16 '11 06:12

Dane O'Connor


People also ask

What does monkey Patch_all () do?

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.

How do you write a constructor function?

//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.

What is object constructor function?

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.


1 Answers

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.

like image 89
RobG Avatar answered Sep 28 '22 03:09

RobG