// 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가 호출되지 않습니다. [바이올린] (http://jsfiddle.net/zkyd58Ly/) – Oriol
@Oriol - 그 시점이 아니지만? 혼합 된 상속은 StateConstructor의 프로토 타입을 state로 설정하지만 호출 된 생성자는 코드에 표시된대로 검사 생성자입니다. –
@TravisJ 작동 방식이 확실치 않지만 OP에서 "*이 코드는 StateConstructor' *를 호출합니다. 그리고 나는 그것을 재현 할 수 없다. – Oriol