TypeError:无法读取未定义的属性...。

时间:2019-02-12 03:55:44

标签: javascript

过去一个小时,我一直在努力寻找线索。当我将其放在IDE中时,intellisense不会出现任何错误,因此我认为没有错别字,但是当我在chrome或node中运行js文件时,会收到以下错误:

  

“ TypeError:无法读取未定义的属性displayQuestion”

这是下面的代码,我要做的就是让它选择随机问题之一,提示用户进行输入,然后在控制台中询问该问题。然后将输入内容与正确答案进行比较。

(function() {

function Question(question, answers, correct){
        this.question = question;
        this.answers = answers;
        this.correct = correct;
    }

Question.prototype.displayQuestion = function(){
    console.log(this.question);

    for(i in this.answers){
        console.log(this.answers[i]);
    }
}

Question.prototype.checkAnswer = function(answer){
    if(answer === correct){
        console.log("Great job! Correct.");
    }
    else{
        console.log("Incorrect. Please try again.");
    }

}

let q1 = Question("Will I eat dinner?", ["Yes", "No"], 0);
let q2 = Question("What is my name?", ["John", "James", "Charles"], 2);
let q3 = Question("Will I go to sleep?", ["Yes", "No"], 1);

let questions = [q1, q2, q3]

let n = Math.floor(Math.random() * questions.length);
questions[n].displayQuestion();
var answer = prompt('Please select the correct answer.');
questions[n].checkAnswer(answer);
})();

3 个答案:

答案 0 :(得分:2)

使用new关键字创建新实例

(function() {

function Question(question, answers, correct){
        this.question = question;
        this.answers = answers;
        this.correct = correct;
    }

Question.prototype.displayQuestion = function(){
    console.log(this.question);

    for(i in this.answers){
        console.log(this.answers[i]);
    }
}

Question.prototype.checkAnswer = function(answer){
    if(answer === correct){
        console.log("Great job! Correct.");
    }
    else{
        console.log("Incorrect. Please try again.");
    }

}

let q1 = new Question("Will I eat dinner?", ["Yes", "No"], 0);
let q2 =  new Question("What is my name?", ["John", "James", "Charles"], 2);
let q3 = Question("Will I go to sleep?", ["Yes", "No"], 1);

let questions = [q1, q2, q3]

let n = Math.floor(Math.random() * questions.length);
questions[n].displayQuestion();
var answer = prompt('Please select the correct answer.');
questions[n].checkAnswer(answer);
})();

答案 1 :(得分:0)

对于function Question,您正在尝试构造一个类。您需要在new调用中调用Question,以返回Question对象。

let q1 = Question("Will I eat dinner?", ["Yes", "No"], 0);
typeof q1 // 'undefined'
let q2 = new Question("What is my name?", ["John", "James", "Charles"], 2);
typeof q2 // 'object'

有关背景知识,请看一下调用一个函数与对该函数调用new之间的区别:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

答案 2 :(得分:0)

您错过了构造函数。尝试添加 new

让q1 =新问题(“我要吃晚饭吗?”,[“是”,“否”],0);