我一直在试图追查过去一小时。当我把它放在我的IDE,没有错误拿出来智能感知,所以我不认为有任何拼写错误,但是当我在Chrome或节点上运行的js文件我收到以下错误:
“类型错误:无法读取的未定义的属性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);
})();
对于function Question
,你想构建一个类。你需要调用new
您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
使用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);
})();
你错过了构造。尝试添加新
让Q1 =新的问题( “我会吃晚饭?”[ “是”, “否”],0);