Game Development Reference
In-Depth Information
As you can see, you can access the variables that are a part of gameCharacter by writing their name
after a dot. JavaScript even allows you to modify the structure of a composite variable after you
have declared and initialized it. For instance, look at the following code:
var anotherGameCharacter = {
name : "Arthur",
skill : "King",
health : 25,
power : 35000
};
anotherGameCharacter.familyName = "Pendragon";
The variable anotherGameCharacter now consists of five parts: name , skill , health , power , and
familyName .
Because variables can also point to functions, you can even include a subvariable that points to a
function. For example, you could define anotherGameCharacter as follows:
var anotherGameCharacter = {
name : "Arthur",
familyName : "Pendragon",
skill : "King",
health : 25,
power : 35000,
healMe : function () {
anotherGameCharacter.health = 100;
}
};
And just as before, you can add a function part to the variable after it has been assigned a value:
anotherGameCharacter.killMe = function () {
anotherGameCharacter.health = 0;
};
You can call these functions in the same way you access the other variables. The following
instruction fully restores the health of the game character:
anotherGameCharacter.healMe();
And if you wanted to kill the character, the anotherGameCharacter.killMe(); instruction would do
the job. The nice thing about structuring variables and functions this way is that you can group
related data and functions together. This example groups variables that all belong to the same game
character. It also adds a few functions that are useful for this game character to have. From now on,
if a function belongs to a variable, I'll call this function a method . I'll call a variable composed of other
variables an object . And if a variable is a part of an object, I'll call this variable a member variable .
You can probably imagine how powerful objects and methods are. They provide a way to bring
structure into a complicated game world. If JavaScript did not have this capability, you would be
obligated to declare a very long list of variables at the beginning of the program, without knowing
 
Search WWH ::




Custom Search