我试图找到我的问题的答案,但我找到的答案真的没有帮助我。我知道这是常见问题,但我找不到正确的答案。这是我的代码:
//Constructor for creating questions
function Question(question, answers, correct) {
this.question = question;
this.answers = answers;
this.correct = correct;
}
//Creating question
var q1 = Question('Is JavaScript the best programming lenguage?', ['Yes', 'No'], 0);
var q2 = Question('What is the name of your teacher?', ['Mike', 'John', 'Jonas'], 2);
var q3 = Question('How would you best describe coding?', ['Boring', 'Fun', 'Tedius', 'Hard'], 1);
//Displaying question and answers
Question.prototype.displayQuestion = function(){
console.log(this.question);
for (var i = 0; i < this.answers.length; i++) {
console.log(i + '. ' + this.answers[i]);
}
}
//Choosing random question
var questions = [q1, q2, q3];
var n = Math.floor(Math.random() * questions.length);
questions[n].displayQuestion();
我一直得到Uncaught TypeError:无法读取challenge.js中未定义的属性'displayQuestion':27先谢谢:)
你打电话给Question(...)
,但你真的打算叫new Question(...)
。
当你在没有Question(...)
的情况下调用new
时,它返回undefined
,因为它没有return
值(同样,this
是window
而不是新对象)。
使用new
时,this
设置为新创建的对象,如果没有return
值,则new Question
调用将返回新创建的this
对象。这肯定是您对代码的期望。
在new
之前使用Question()
关键字