In the following code I do not understand why the score variable in the sc() function is not being reset to 0 each time a question is asked ? The code works properly but each time the sc function is invoked by the checkAnswer method why is score not reset to 0?
(function () {
var Question = function (question, answers, correct) {
this.question = question;
this.answers = answers;
this.correct = correct;
};
Question.prototype.displayQuestion = function () {
console.log(this.question);
for (i = 0; i < this.answers.length; i++) {
console.log(i + ' : ' + this.answers[i]);
}
};
Question.prototype.checkAnswer = function (ans, callback) {
// var sc;
if (ans === this.correct) {
console.log('correct');
sc = callback(true);
} else {
console.log('incorrect');
sc = callback(false);
}
this.displayScore(sc);
};
Question.prototype.displayScore = function (score) {
console.log('Your current score is :' + score);
console.log('______________________________');
};
var q1 = new Question('Whats the best dog breed?', ['Staffy', 'Boxer', 'Pug'], 0);
var q2 = new Question('Whats the best name?', ['Donna', 'Mary', 'Jane'], 0);
var q3 = new Question('Whats the best city?', ['Sydney', 'Perth', 'Melbourne'], 1);
var qArray = [q1, q2, q3];
function sc() {
var score = 0;
return function (correct) {
if (correct) {
score++;
}
return score;
}
}
var keepScore = sc();
function askNextQuestion() {
var randQuestion = [Math.floor(Math.random() * qArray.length)];
qArray[randQuestion].displayQuestion();
var askPlayer = prompt('What is the best answer? - enter the answer number');
if (askPlayer != 'exit') {
qArray[randQuestion].checkAnswer(parseInt(askPlayer), keepScore);
askNextQuestion();
}
}
askNextQuestion();
})();