【问题标题】:Javascript inheritance and function overridingJavascript继承和函数覆盖
【发布时间】:2015-01-02 20:29:10
【问题描述】:
// Base state class -------------------------
function StateConstuctor()
{

}

// Inherited learn class --------------------
function StateLearnConstructor()
{

}

// Inherited exam class ---------------------
function StateExamConstructor()
{

}


function extend(Child, Parent)
{
    var F = function() { }
    F.prototype = Parent.prototype
    Child.prototype = new F()
    Child.prototype.constructor = Child
    Child.superclass = Parent.prototype
}


function createState(rollType)
{
    if (rollType == 'learn')
    {
        extend(StateLearnConstructor, StateConstuctor);
        var state = new StateLearnConstructor();

        return state;
    }
    else if (rollType == 'exam')
    {
        extend(StateExamConstructor, StateConstuctor);
        var state = new StateExamConstructor();

        return state;
    }
}

StateConstuctor.prototype.getTitles = function()
{
   console.log('base "virtual" function');
}
StateLearnConstructor.prototype.getTitles = function()
{
   console.log('learn');
}
StateExamConstructor.prototype.getTitles = function()
{
   console.log('exam');
}

您好,我有以下“OOP”结构,我想在 C++ 中模拟类似虚函数的东西。所以我在StateConstructor 中有基本的虚函数,每个子类都有不同的实现。

var state = createState('exam');
state.getTitles();

但是这段代码调用了StateConstructor 基本虚函数。这里有什么问题?

【问题讨论】:

  • StateConstuctor 未被调用。 fiddle
  • @Oriol - 这不是重点吗?混合继承将 StateConstructor 的原型设置为 state,但调用的构造函数是考试构造函数,如代码所示。
  • @TravisJ 不确定它应该如何工作,但 OP 说“此代码调用 StateConstructor”。我无法重现。
  • @Oriol 不,OP 说“此代码调用 StateConstructor 基本虚函数”。换句话说“这段代码调用StateConstructor上的基本虚函数”。

标签: javascript oop inheritance


【解决方案1】:

createState() 正在为您的StateLearnConstructor 和您的StateExamConstructor 覆盖prototype,在您为其分配功能后。

您不应该有条件地扩展它们。只需扩展它们:

extend(StateLearnConstructor, StateConstuctor);
extend(StateExamConstructor, StateConstuctor);

StateConstuctor.prototype.getTitles = function () {
    console.log('base "virtual" function');
};
StateLearnConstructor.prototype.getTitles = function () {
    console.log('learn');
};
StateExamConstructor.prototype.getTitles = function () {
    console.log('exam');
};

function createState(rollType) {
    if (rollType == 'learn') {
        return new StateLearnConstructor();
    } else if (rollType == 'exam') {
        return new StateExamConstructor();
    }
}

一旦你这样做了,你的“虚拟功能”应该会按预期工作。

demo

注意:您对extend() 的实现比它需要的更复杂。继承原型的现代方式是使用Object.create()

function extend(Child, Parent) {
    Child.prototype = Object.create(Parent.prototype);
    Child.prototype.constructor = Child;
    Child.superclass = Parent.prototype;
}

【讨论】:

    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 2011-09-04
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多