Grace Huang
Grace Huang

Reputation: 5679

Extend a prototype method

Now I have a prototype like:

function A() {}

A.prototype.run =  function () {
    console.log('run 1');
};

Given that I cannot change anything where A is at (no control over the source). I would like to extend the method run. Not only log run 1, also log run 2. I tried several different approaches, it does not work.

A.prototype.run = function () {
    this.run.call(this);
    console.log('run 2');
}

Or

A.prototype.run = function () {
    arguments.callee.call(this);
    console.log('run 2');
}

Anyone having a solution for this? I would rather not to copy what's inside the method run. Thanks!

Upvotes: 0

Views: 74

Answers (2)

epascarello
epascarello

Reputation: 207501

A.prototype._run = A.prototype.run;
A.prototype.run = function () {
    this._run.call(this);
    console.log('run 2');
}

Upvotes: 1

Matt
Matt

Reputation: 75307

You can override the run method, saving a reference to it as such;

(function (orig) {

    A.prototype.run = function () {
        orig.apply(this, arguments);

        console.log('run 2');
    }

}(A.prototype.run));

This is similar to your first attempt, but preserves the first value of run, so you can effectively do this.run.call(this) as you attempted.

Upvotes: 1

Related Questions