繁体   English   中英

为什么会出现Uncaught TypeError:无法读取未定义的属性'displayQuestion'?

[英]Why am i getting Uncaught TypeError: Cannot read property 'displayQuestion' of undefined?

我试图找到问题的答案,但实际上我在这里找不到的答案对我有帮助。 我知道这是常见问题,但我找不到正确的答案。 这是我的代码:

    //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值(也, thiswindow ,而不是一个新的对象)。

当您使用newthis被设置为一个新创建的对象,并且如果没有return值,则new Question调用将返回新创建的this对象。 当然,这就是您期望代码执行的操作。

Question()之前使用new关键字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM