【发布时间】: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