用作参数

时间:2018-10-01 17:06:18

标签: javascript

方法checkAnswer无法传递参数keepScore。它可以证明回调不是函数:如何构造回调,以便checkAnswer可以使用第二个参数keepScore?

(function() {

  function Question(question, answers, correct) {

    this.question = question;

    this.answers = answers;

    this.correct = correct;

  }

  //Display questions and answers
  Question.prototype.displayQuestion = function() {

    console.log(this.question);
    for (let index = 0; index < this.answers.length; index++) {

      console.log(index + ": " + this.answers[index]);

    }
  }

  //Checking for correct answers
  Question.prototype.checkAnwers = function(ans, callback) {
    var sc;

    if (ans === this.correct) {

      console.log('Correct answer');

      sc = callback(true);

    } else {

      console.log('Wrong answer')

      sc = callback(false);

    }

    this.displayScore(sc);
  }

  //Display Scores to the console
  Question.prototype.displayScore = function(score) {

    console.log('Your current score is: ' + score);

    console.log('---------------------------------');
  }

  //Populate questions, answers and correct answers
  var q1 = new Question('Atom is the smallest particle of matter?', ['Yes', 'No'], 0);

  var q2 = new Question('The element with atomic number of 16 is  ?', ['silicon', 'sulphur', 'sodium'], 2);

  var q3 = new Question('One of the easiest language to learn is ', ['Javascript', 'Python', 'Java'], 1);

  var questions = [q1, q2, q3];

  for (let index = 0; index < questions.length; index++) {

    questions[index].displayQuestion();

    var answer = prompt('Please enter the correct answer number');

    if (answer === 'exit') {

      break;

    } else {

      questions[index].checkAnwers(parseInt(answer), keepScore);

    }
  }

  //Scoring the quiz
  function score() {

    var sc = 0;

    return function(correct) {

      if (correct) {

        sc++;

      }

      return sc;
    }

  }

  var keepScore = score();

})();

1 个答案:

答案 0 :(得分:1)

代码中的问题是

var keepScore = score();

由于for loop永远不会执行,因此keepScore函数中未定义checkAnswers

您需要移动

var keepScore = score();

for loop之前。