我有以下代码,我需要一些澄清。在我继续之前,我想要完全理解它。我知道这个例子可能很愚蠢,我相信有很多更好的方法来解决这个问题,但是为了这一课,这个人使用了这个例子。
我所需要的就是弄清楚score函数的流程是如何工作的。这些值从何而来?这个人每次给出正确答案的时候是怎么加起来的呢?我主要想了解的是,每当用户在警报中输入真值时,此代码如何生成要显示给控制台的数字。如果我讲得不清楚,我很抱歉,我只需要理解function score()
和更高版本的代码是如何工作的。我无论如何也想不出这件事。sc从哪里获得它的值,它也从哪里传递它;和;和。有没有人愿意告诉我这个代码是如何组合在一起的。我将永远心存感激。
(function() {
function Question(question, answers, correct) {
this.question = question;
this.answers = answers;
this.correct = correct;
}
Question.prototype.displayQuestion = function() {
console.log(this.question);
for (var 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 answer!');
sc = callback(true);
} else {
console.log('Wrong answer. Try again :)');
sc = callback(false);
}
this.displayScore(sc);
}
Question.prototype.displayScore = function(score) {
console.log('Your current score is: ' + score);
console.log('------------------------------');
}
var q1 = new Question('Is JavaScript the coolest programming language in the world?',
['Yes', 'No'],
0);
var q2 = new Question('What is the name of this course\'s teacher?',
['John', 'Micheal', 'Jonas'],
2);
var q3 = new Question('What does best describe coding?',
['Boring', 'Hard', 'Fun', 'Tediuos'],
2);
var questions = [q1, q2, q3];
function score() {
var sc = 0;
return function(correct) {
if (correct) {
sc++;
}
return sc;
}
}
var keepScore = score();
function nextQuestion() {
var n = Math.floor(Math.random() * questions.length);
questions[n].displayQuestion();
var answer = prompt('Please select the correct answer.');
if(answer !== 'exit') {
questions[n].checkAnswer(parseInt(answer), keepScore);
nextQuestion();
}
}
nextQuestion();
})();
发布于 2019-05-25 16:44:30
这里的得分函数是一个闭包
当调用score时,sc inside score的状态被初始化。
var keepScore = score();
现在keepScore包含由闭包返回的函数,即
function (correct) {
if (correct) {
sc++; // it has a "closure" over it
}
return sc;
}
它接受布尔值。即keepScore(true)或keepScore(false)
现在,此keepScore函数被传递给check answer
questions[n].checkAnswer(parseInt(answer), keepScore);
在check anwer中,如果答案正确,则会将true传递给keepScore
callback(true) <=> keepScore(true)
如果您想更清楚地了解闭包,可以阅读这篇文章
https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#closure
https://stackoverflow.com/questions/56302747
复制相似问题