Game Development Reference
In-Depth Information
Here, you call the
random
function that is defined as a part of the
Math
object, and you store its result in
the variable
n
. Apparently,
random
provides a result value that can be stored. The
Canvas2D.drawImage
method on the other hand doesn't provide a result that you can store in a variable. Of course, the
method does have an effect of some sort, because it draws a sprite on the screen, which could also
be considered a result of the method call. However, when I talk about the
result
of a method, I don't
mean the method has some effect on an object. I mean the
method call
returns a value that can be
stored in a variable. This is also called the
return value
of a method or function. In mathematics, it's
common that a function has a result. A mathematical function
fx=x
2
()
takes as parameter an
x
value and it returns its square as a result. You could write this mathematical function in JavaScript
if you wanted to:
var square = function(x) {
return x*x;
}
If you look at the header of this method, you see that it takes one parameter called
x
. Because the
function returns a value, you can store that value in a variable:
var sx = square(10);
After this instruction is executed, the variable
sx
will contain the value 100. In the function body, you
can indicate using the keyword
return
what the actual value is that the function returns. In the case
of
square
, the function returns the outcome of the expression
x*x
. Note that executing the
return
instruction also terminates execution of the rest of the instructions in a function. Any instructions
placed
after
the
return
instruction are not executed. For example, consider the following function:
var someFunction = function() {
return 12;
var tmp = 45;
}
In this example, the second instruction (
var tmp = 45;
) will never be executed because the
instruction before it ends the function. This is a very handy feature of the
return
instruction, and you
can use it to your advantage:
var squareRoot = function(x) {
if (x < 0)
return 0;
// Calculate the square root, we are now sure that x >=0.
}
In this example, you use the
return
instruction as a safeguard against wrong input by the user of the
method. You can't calculate the square root of a negative number, so you handle the case where
x
is
negative before you do any calculations or raise any annoying, potentially hard-to-debug errors.
An example of a method that doesn't have a return value is
cannon.handleInput
. Because this
method doesn't have a return value, you don't need to use the
return
keyword in the body of the
method, although doing so can sometimes still be useful. For example, suppose you only want to
Search WWH ::
Custom Search