0

I would like to modifiy a prototyped function of an external library in order to execute some code before that function when it is called. I though to clone that function and then replace it by a new one like so:

Note that I am using a clone function found in another question

This is a simplified example:

var oldFunction = anObject.aFunction.clone();
anObject.aFunction = function(a, b, c) {
    if (a > b) {
        return;
    } else {
       oldFunction(a, b, c);
    }
}

Function.prototype.clone = function() {
    var that = this;
    var temp = function temporary() { return that.apply(this, arguments); };
    for(var key in this) {
        if (this.hasOwnProperty(key)) {
            temp[key] = this[key];
        }
    }
    return temp;
};

However, doing so, the oldFunction seem to lose all its original reference to this.

Is there a solution?

Community
  • 1
  • 1
Below the Radar
  • 7,321
  • 11
  • 63
  • 142

2 Answers2

1

You need to call it with the correct this:

oldFunction.call(this, a, b, c);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

I don't think you need to clone the function, just keep a reference to it. Or more accurately, create a copy of the function with the correct this binding.

var oldFunction = anObject.aFunction.bind(anObject);
anObject.aFunction = function(a, b, c) { ... };

bind creates a copy of the given function with this specified by the first argument. It can also be used to bind arguments as well.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91