【问题标题】:Why am i getting Uncaught TypeError: Cannot read property 'displayQuestion' of undefined?为什么我收到未捕获的类型错误:无法读取未定义的属性“displayQuestion”?
【发布时间】:2019-04-30 08:46:00
【问题描述】:

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

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

我一直在 未捕获的类型错误:无法读取未定义的属性“displayQuestion” 在挑战.js:27 在此先感谢:)

【问题讨论】:

  • new Question ? ps,为防止意外调用构造函数类型函数,请将其添加为第一行 -> 'use strict'; if (!this) throw new Error("Call with new");

标签: javascript


【解决方案1】:

你打电话给Question(...),但你真的是想打电话给new Question(...)

当您在没有new 的情况下调用Question(...) 时,它会返回undefined,因为它没有return 值(另外,thiswindow 而不是一个新对象)。

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

【讨论】:

  • 谢谢!这对我帮助很大
【解决方案2】:

Question()之前使用new关键字

【讨论】:

    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2015-01-06
    • 2017-07-26
    相关资源
    最近更新 更多