[英]Why am i getting Uncaught TypeError: Cannot read property 'displayQuestion' of undefined?
I tried to find the answer to my problem but really non of the answers i found here helped me. 我试图找到问题的答案,但实际上我在这里找不到的答案对我有帮助。 I know this is commonly asked question but i couldn't find right answer.
我知道这是常见问题,但我找不到正确的答案。 Here is my code:
这是我的代码:
//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();
I keep getting Uncaught TypeError: Cannot read property 'displayQuestion' of undefined at challenge.js:27 Thanks in advance :) 我不断收到Uncaught TypeError:无法读取Challenge.js中未定义的属性“ displayQuestion”:27提前感谢:)
You are calling Question(...)
but you really mean to call new Question(...)
. 您正在呼叫
Question(...)
但实际上是要呼叫new Question(...)
。
When you call Question(...)
without new
, it returns undefined
because it has no return
value (also, this
is window
instead of a new object). 当你调用
Question(...)
没有new
,它返回undefined
,因为它没有return
值(也, this
是window
,而不是一个新的对象)。
When you use new
, this
is set to a newly-created object, and if there's no return
value, the new Question
call returns the newly-created this
object. 当您使用
new
, this
被设置为一个新创建的对象,并且如果没有return
值,则new Question
调用将返回新创建的this
对象。 That's certainly what you expect your code to do. 当然,这就是您期望代码执行的操作。
在Question()
之前使用new
关键字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.