Game Development Reference
In-Depth Information
and now the following instructions:
var someNumber = 10;
square(someNumber);
After executing these instructions, the value of
someNumber
still is 10 (and not 100). Why is this?
Because when the
square
function is called, the number parameter is passed
by value
. The variable
f
is a local variable in the method that initially contains the value of the
someNumber
variable. In the
method, the local variable
f
is changed to contain
f * f
, but this doesn't change the
someNumber
variable, because it's another location in memory. Because non-primitive objects are passed by
reference
, the following example will result in a changed value of the object passed as a parameter:
function square(obj) {
obj.f = obj.f * obj.f;
}
var myObject = { f : 10 };
square(myObject);
// myObject.f now contains the value 100.
Whenever a JavaScript script is running, there are a number of references and values in memory.
For example, if you look at Figures
11-2
and
11-3
, you see that the
Ball
objects contain both values
and references to other objects (such as
Vector2
objects or
Image
objects).
Null and Undefined
Whenever you declare a variable in JavaScript, initially its value is set to
undefined
:
var someVariable;
console.log(someVariable); // will print 'undefined'.
In JavaScript, you can also indicate that a variable is defined but currently doesn't refer to any
object. This is done by using the
null
keyword:
var anotherCannon = null;
Because you haven't yet created an object (using the
new
keyword), the memory looks like what is
depicted in Figure
11-10
.
anotherCannon
null
Figure 11-10.
A variable pointing to
null
So, indicating that a variable isn't yet pointing to anything is done by assigning
null
to it. It's even
possible to check in a JavaScript program whether a variable is pointing to an object or not, like this:
if (anotherCannon === null)
anotherCannon = new Cannon();
Search WWH ::
Custom Search