HTML and CSS Reference
In-Depth Information
Using the
this
Keyword
The
this
keyword
is a special JavaScript keyword that refers to the object that calls or
owns a particular function or method. In the code you just entered, the swapPuzzle()
function will be run whenever one of the puzzle buttons is clicked. When that happens,
the button that initiated the function is the function's owner, and its properties and meth-
ods can be referenced using the
this
keyword. For example, each of the puzzle buttons
supports the
id
attribute. Therefore, if you wanted to access the
id
value of the button
that was clicked by the user, you would use the following expression:
this.id
Thus, if the second button were clicked, this expression would return the text string
puzzle2
because that's the value of the
id
attribute for the second puzzle button. In the
same way, each puzzle button supports the
value
attribute; to access the value of the
clicked button, you would use the following object reference:
When used with event
handler attributes placed
in an HTML document, the
this
keyword references
the
window
object.
this.value
If the second puzzle button were clicked, the expression
“Hanjie “ + this.value
would return the text string
Hanjie Puzzle 2
because the second puzzle button's
value
attribute is equal to the text string
Puzzle 2
.
However, what we want is to access the variables associated with each puzzle
because the
puzzle1
,
puzzle1Hint
, etc., variables contain the information we want dis-
played in the page. We can access the variables using the
eval()
function introduced in
Tutorial 11. Recall that the
eval()
function evaluates a text string as a piece of JavaScript
code. Therefore, an expression such as
eval(“puzzle2”)
is evaluated as a reference to the
puzzle2
variable, and the expression
eval(this.id)
also references the
puzzle2
variable if the second button were clicked. In the same way,
the expression
eval(this.id + “Hint”)
would reference the
puzzle2Hint
variable when the second button is clicked. You'll use
the
this
keyword and the
eval()
function now to create variables in the swapPuzzle()
function to reference the variables that store each puzzle's title, hint, difficulty rating, and
puzzle grid.
To create the swapPuzzle() function:
◗
1.
Within the
hanjie.js
file, add the following function directly below the init() func-
tion, as shown in Figure 13-11:
function swapPuzzle() {
/* Determine the puzzle to show based on the button's id value
*/
var title = “Hanjie “ + this.value;
var hint = eval(this.id + “Hint”);
var rating = eval(this.id + “Rating”);
var puzzle = eval(this.id);
}