Javascript继承和函数覆盖

时间:2015-01-02 20:29:10

标签: javascript oop inheritance

// 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基本虚函数。这里有什么问题?

1 个答案:

答案 0 :(得分:2)

在您为其分配功能后,

createState()会覆盖prototypeStateLearnConstructor的{​​{1}}。

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

StateExamConstructor

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

demo

注意: 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(); } } 的实施比实际需要的更复杂。继承原型的现代方法是使用extend()

Object.create()