Javascript类“对象没有方法错误”

时间:2013-10-21 18:44:08

标签: javascript

我有一个叫做问题的课程。我试图通过创建其correspoding对象从另一个类调用此显示方法。但是我得到了这个错误。如果你能帮助我,我会很高兴的。

///////////////QUESTION///////////////
function Question(id, text){
    this.id = id;
    this.text = text;
}

function QType1(id, text, choices, answers){
//this is true or false
    Question.call(this, id, text) ;
    this.choices = choices;
   this.answers = answers;
}

QType1.prototype = new Question();

//inherit Question
QType1.prototype.constructor = QType1;

QType1.Display = function(){
    console.log("Display Question");
}

///////////////QUIZ//////////////////
function quiz(){}

quiz.prototype.SetHomeScreen = function(x,y){
    var svgCanvas = CreateCanvas(x,y);
    AddText(svgCanvas,100,50, quiz_input.Settings.Layout.Text);
    console.log("Text Added");
    start_but = AddStartButton(svgCanvas, 300, 250);
    console.log("start button Added");
    start_but
    .on("click", function(d,i) {
                            startquiz();
                                });
    var startquiz = function(){
        console.log(this);
        quiz.prototype.StartQuiz();
    };

}

quiz.prototype.question_objs = [];
quiz.prototype.user_ans = [];
quiz.prototype.corr_ans = [];

quiz.prototype.LoadQuestions = function(){
    for(var i=0, l=questions.length; i<l; i++){
           this.question_objs.push(new QType1(questions[i].id, questions[i].settings.text, questions[i].settings.choices, questions[i].settings.answers));
        }
    console.log(this.question_objs);
}

quiz.prototype.DisplayQuestions = function(){
    var i = 0;
    var l = this.question_objs.length;
    while(i < l){
        console.log(this.question_objs[i] instanceof QType1);
        this.question_objs[i].Display();
    }

}
quiz.prototype.StartQuiz = function(){
        quiz.prototype.LoadQuestions();
        console.log("Starting Quiz");
        quiz.prototype.DisplayQuestions();
}

我得到的错误信息是。 enter image description here 在此先感谢

1 个答案:

答案 0 :(得分:1)

两个可能的原因:

  1. 您没有声明function Qtype1() {}
  2. 你没有像var q = new Qtype1()
  3. 那样实例化qtype1对象

    编辑 :您没有使用显示QType1的方法。 您可以使用QType1.Display方法的唯一方法是将QType1声明为变量,例如var QType1 = {} 这样你就可以将Display方法直接绑定到变量上。但是,当您将其声明为构造函数时,您需要QType1.prototype.Display = function () { console.log('Display question...'); };

    另外 - 你的继承有点乱。您正在调用Question.call(this, id, text),然后您声明QType1.prototype = new Question(),然后对构造函数执行相同的操作。您需要稍微检查一下您的javascript原型继承理论。

相关问题