javascript - 类型错误 : Cannot read property . ... 未定义

标签 javascript

在过去的一个小时里我一直在努力寻找。当我将其放入 IDE 中时,智能感知不会出现任何错误,因此我认为没有任何拼写错误,但是当我在 chrome 或 Node 中运行 js 文件时,我收到以下错误:

"TypeError: Cannot read property displayQuestion of undefined"

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

(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);
})();

最佳答案

使用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);
})();

关于javascript - 类型错误 : Cannot read property . ... 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54642567/

相关文章:

javascript - 如何在 javascript 中将列填充添加到特定表的第一列?

javascript - DOM 中的 $scope 值为 null

javascript - Nightmare 在循环内迭代

javascript - Accessibility - React 确保点击事件有按键事件

javascript - 为什么 continue 语句在此循环中不起作用?

javascript - promise 不等待完成

php - 联系表单默认值验证

javascript - 页面在更新之前等待所有 AJAX 调用完成

javascript - 如何使用 jquery 滚动到具有动态 id 的元素

javascript - 使用 Flask 在 Javascript 上提供 json 数据