在javascript中,新对象函数如何扩展同名原型函数?

时间:2011-08-21 05:36:45

标签: javascript object prototype-programming

创建对象时,我希望使用新函数扩展现有原型函数的功能。新函数需要调用原始的原型函数来执行,但它们显然位于相同的命名空间中。

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) } );

如果ORIGINAL为this.fn,那么o1.fn将成为非终止递归

如何在Obj.prototype.fn()内引用o1.fn()


回答,根据@PeterOlsen,

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

2 个答案:

答案 0 :(得分:2)

  

如何从o1.fn()中引用Obj.prototype.fn()?

很简单,用Obj.prototype.fn引用它。

答案 1 :(得分:1)

你应该能够到达那里,你可能需要比你想象的更远一点。尝试像

这样的东西
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) } );

在闭包中,获取用于创建此对象的构造函数的原型,然后使用.apply()使用this和传入的参数调用所需的实例方法。 / p>

或者像Peter Olson所说的那样,您可以使用this.constructor.prototype.fn代替Obj.prototype.fn,但仍需要使用.call().apply(),以确保执行正确范围内的方法,否则this不会指向您认为应该的内容。