![](/img/trans.png)
[英]why am I getting Uncaught TypeError: Cannot read property '0' of undefined on assign?
[英]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
值(也, this
是window
,而不是一個新的對象)。
當您使用new
, this
被設置為一個新創建的對象,並且如果沒有return
值,則new Question
調用將返回新創建的this
對象。 當然,這就是您期望代碼執行的操作。
在Question()
之前使用new
關鍵字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.