Search code examples
javascriptobjectprototype-programming

in javascript, how does a new object function extend a prototype function of same name?


when creating an object I wish to extend the functionality of an existent prototype function with a new function. the new function needs to call the original prototype function to perform, but they are apparently in the same namespace.

Obj = function(i,newFn) {
   this.i = i;
   if( newFn ) this.fn = newFn;
}
Obj.prototype.fn = function(a) { return a+this.i; }

o1 = new Obj1( 3, function(a) { if( a<0 ) return 0; return ORIGINAL.fn(a) } );

if ORIGINAL is this.fn then o1.fn becomes non-terminating recursive

how do I reference Obj.prototype.fn() from within o1.fn()?


answer, as per @PeterOlsen,

o1 = new Obj1( 3, function(a) { return Obj.prototype.fn.call(this,a) } );

Solution

  • You should be able to get there, you just might have to go a little farther than you expected. Try something like

    Obj = function(i,newFn) {
       this.i = i;
       if( newFn ) this.fn = newFn;
    }
    Obj.prototype.fn = function(a) { return a+this.i; }
    
    o1 = new Obj( 3, function(a) { if( a<0 ) return 0; return this.constructor.prototype.fn.apply(this, arguments) } );
    

    In your closure, get the prototype for the constructor that was used to make this object, and then use .apply() to invoke the instance method you want using this and the arguments you passed in.

    Or like Peter Olson said, instead of this.constructor.prototype.fn you can use Obj.prototype.fn, but you still need to use either .call() or .apply(), to make sure that you execute the method in the right scope, otherwise this wont point to what you think it should.