Java Reference
In-Depth Information
• The variable interval changes to this.interval and the call to the
countDown() function becomes a call to the this.countDown() method.
It also has to be bound to the this object (otherwise the value of this in the
this.countDown() method will be the window object).
• The event listener also needs to be bound to this so that it can call the
this.check() method; otherwise the value of this will be the form element.
The nested functions that were inside the play() function now become methods of the
Game.prototype object. Most of these methods are the same as their equivalent func-
tions in the previous chapter, except that the variables that are properties of the instance
need this placing in front of them, such as this.questions , this.score and
this.time . The method calls also need this placing in front of them as they are meth-
ods of the Game instance such as this.gameOver() :
// Method definitions
Game.prototype.chooseQuestion = function() {
console.log("chooseQuestion() called");
var questions =
this.questions.filter(function(question){
return question.asked === false;
});
// set the current question
this.question = questions[random(questions.length) -
1];
this.ask(this.question);
}
In the Game.prototype.ask() method we need to create a temporary variable called
quiz that is set equal to this . This allows us to refer to the Game object as quiz inside
the nested chooseOption() function because the value of this changes to the win-
dow object inside nested functions.
Game.prototype.ask = function(question) {
console.log("ask() called");
var quiz = this;
// set the question.asked property to true so it's not
asked again
Search WWH ::




Custom Search