Game Development Reference
In-Depth Information
Looking at the previous example using the number type, you would expect that there are now two
Cannon
objects in memory: one stored in the variable
cannon1
, and one stored in
cannon2
. However,
this isn't the case! Actually, both
cannon1
and
cannon2
refer to the same object
. After the first
instruction (creating the
Cannon
object), the memory is shown in Figure
11-8
.
Cannon
cannon1
...
© Springer-Verlag Berlin Heidelberg 2013
Figure 11-8.
A
Cannon
object in memory
Here, you see that there is a big difference between how basic types such as numbers and Booleans
are represented in memory as opposed to more complicated types such as the
Cannon
class. In
JavaScript, all objects that aren't primitive types, such as numbers, Booleans, and characters, are
stored as
references
as opposed to values. This means a variable such as
cannon1
doesn't directly
contain the
Cannon
object, but it contains
a reference to it
. Figure
11-8
indicate that
cannon1
is a
reference by representing it as a block containing an arrow to an object. If you now declare the
cannon2
variable and assign the value of
cannon1
to it, you can see the new situation in Figure
11-9
.
Cannon
cannon1
...
cannon2
© Springer-Verlag Berlin Heidelberg 2013
Figure 11-9.
Two variables that refer to the same object
The result is that if you change the color of the cannon as follows
cannon2.color = Color.red;
then the expression
cannon1.color
will be
Color.red
, because both
cannon1
and
cannon2
refer to the
same object! This also has an effect on how objects are passed around in methods. For example,
the constructor method of
ThreeColorGameObject
expects three sprites as a parameter. Because
sprites aren't a basic type in JavaScript, you're actually passing references to these sprites. In
theory, this means you could modify the sprites in the
ThreeColorGameObject
constructor. Passing
basic types such as numbers as parameters to methods happens
by value
, so changing the value in
the method has no effect. Consider the following function
function square(f) {
f = f * f;
}
Search WWH ::
Custom Search