[英]Uncaught TypeError: undefined is not a function, object created in for loop
我正在构建一个小的测验应用程序,用户可以在其中构建自己的测验,但在for循环中创建对象时遇到了问题。
这是Question对象的构造函数:
var question = function(questionNumber, question, choices, correctAnswer) {
this.questionNumber = questionNumber;
this.question = question;
this.choices = choices;
this.correctAnswer = correctAnswer; //The number stored here must be the location of the answer in the array
this.populateQuestions = function populateQuestions() {
var h2 = $('<h2>').append(this.question);
$('#quizSpace').append(h2);
for (var i = 0; i < choices.length; i++) {
//Create the input element
var radio = $('<input type="radio">').attr({value: choices[i], name: 'answer'});
//Insert the radio into the DOM
$('#quizSpace').append(radio);
radio.after('<br>');
radio.after(choices[i]);
}
};
allQuestions.push(this);
};
我有一堆动态生成的HTML然后从中提取值并将它们放在一个新对象中,如下所示:
$('#buildQuiz').click(function() {
var questionLength = $('.question').length;
for ( var i = 1; i <= questionLength; i++ ) {
var questionTitle = $('#question' + i + ' .questionTitle').val();
var correctAnswer = $('#question' + i + ' .correctAnswer').val() - 1;
var inputChoices = [];
$('#question' + i + ' .choice').each(function(){
inputChoices.push($(this).val());
});
var question = new question(i, questionTitle, inputChoices, correctAnswer);
}
allQuestions[0].populateQuestions();
$('#questionBuilder').hide();
$('#quizWrapper').show();
});
但是,当我单击#buildQuiz按钮时,我收到错误:
Uncaught TypeError: undefined is not a function
在这一行:
var question = new question(i, questionTitle, inputChoices, correctAnswer);
那是因为行var question = new question(i, questionTitle, inputChoices, correctAnswer);
这会在其范围内创建另一个变量question
,即在click事件处理程序中。 由于可变的提升,它被移动到范围(功能)的顶部,最终变为:
$('#buildQuiz').click(function() {
var question; //undefined
...
...
//here question is not the one (constructor) in the outer scope but it is undefined in the inner scope.
question = new question(i, questionTitle, inputChoices, correctAnswer);
只需将变量名称更改为其他名称即可尝试。
var qn = new question(i, questionTitle, inputChoices, correctAnswer);
或者为了避免这些问题,您可以在Pascalcase中命名构造函数,即
var Question = function(questionNumber, question, choices, correctAnswer) {
.....
你用undefined
来覆盖全局question
var。 以下相当于你拥有的:
$('#buildQuiz').click(function() {
var question; // this is why `question` is undefined
var questionLength = $('.question').length;
for ( var i = 1; i <= questionLength; i++ ) {
var questionTitle = $('#question' + i + ' .questionTitle').val();
var correctAnswer = $('#question' + i + ' .correctAnswer').val() - 1;
var inputChoices = [];
$('#question' + i + ' .choice').each(function(){
inputChoices.push($(this).val());
});
question = new question(i, questionTitle, inputChoices, correctAnswer);
}
allQuestions[0].populateQuestions();
$('#questionBuilder').hide();
$('#quizWrapper').show();
});
您需要使用不同的变量名称,或者将您的类重命名为大写第一个字母(这是非常标准的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.