JavaScript中的继承:调用父方法

时间:2014-07-10 14:10:56

标签: javascript oop inheritance

我在JavaScript中实现继承的方式如下例所示。我试图从子类调用父类的方法。我在网上看过很多例子,它们将父方法添加到原型中,并使用call或apply函数(但我的实现并没有这样做)。有没有办法进行这种类型的通话?

function classM() //parent class
{
    this.myName = function()
    {
        console.log('parent');
    }
}

function classEM ()
{
    classM.call(this);

    this.myName = function()
    {
        console.log('child');
        //HOW DO I CALL myName() of the parent class?
    }

}


classEM.prototype = Object.create(classM.prototype);
classEM.prototype.constructor = classEM;




var rm = new classEM();
rm.myName(); //should print child and then parent

1 个答案:

答案 0 :(得分:2)

当您在this.myName = ...中执行classEM时,您正在将父级创建的旧myName函数替换为classEM中的函数。所以现在只存在一个功能。相反,您可以在myName的原型中添加classM函数并从中继承。

所以程序就像这样

function classM() {}

// Add myName to the parent
classM.prototype.myName = function() {
    console.log('parent');
}

function classEM() {
    this.myName = function() {
        // Get the parent prototype object and invoke the myName in it.
        Object.getPrototypeOf(this).myName();
        console.log('child');
    }
}

classEM.prototype = Object.create(classM.prototype);
classEM.prototype.constructor = classEM;

var rm = new classEM();
rm.myName();

<强>输出

parent
child
相关问题