在重写方法中调用父对象

时间:2015-09-07 13:16:39

标签: javascript oop override super

我正在设计我自己的OOP js模式,但是当我想覆盖一个方法时我遇到了问题。

C1 = function () {};
C1.prototype.method = function ()
{
    // Do stuff
};

C2 = function () {};
C2.prototype = new C1();
C2.prototype.constructor = C2;
C2.prototype.parentClass = C1;
C2.prototype.method = function ()
{
    // Not valid here! 'this.parentClass' references C2 instead of C1
    // when 'this' is a C3 instance.
    this.parentClass.prototype.method.call (this);
    // Do stuff
};

C3 = function () {};
C3.prototype = new C2();
C3.prototype.constructor = C3;
C3.prototype.parentClass = C2;
C3.prototype.method = function ()
{
    this.parentClass.prototype.method.call (this);
    // Do stuff
};

var c3 = new C3 ();
c3.method ();

有人建议:

[parentClassName].prototype.method.call (this);

但是,通过这种方式,有必要编写(并知道)父类的名称。我想以更优雅的方式做到这一点。

是否有另一种方法来引用父重写方法而不编写父类名?

0 个答案:

没有答案
相关问题