在过去的一个小时里我一直在努力寻找。当我将其放入 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/