未捕获的TypeError:undefined不是函数,在for循环中创建的对象

fed*_*rce 4 javascript jquery object

我正在构建一个小的测验应用程序,用户可以在其中构建自己的测验,但在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);
};
Run Code Online (Sandbox Code Playgroud)

我有一堆动态生成的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();
});
Run Code Online (Sandbox Code Playgroud)

但是,当我单击#buildQuiz按钮时,我收到错误:

Uncaught TypeError: undefined is not a function 
Run Code Online (Sandbox Code Playgroud)

在这一行:

var question = new question(i, questionTitle, inputChoices, correctAnswer);
Run Code Online (Sandbox Code Playgroud)

PSL*_*PSL 6

这是因为在其范围内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);
Run Code Online (Sandbox Code Playgroud)

只需将变量名称更改为其他名称即可尝试.

     var qn = new question(i, questionTitle, inputChoices, correctAnswer);
Run Code Online (Sandbox Code Playgroud)

或者为了避免这些问题,您可以在Pascalcase中命名构造函数,即

 var Question = function(questionNumber, question, choices, correctAnswer) {
 .....
Run Code Online (Sandbox Code Playgroud)