Game Development Reference
In-Depth Information
So what is the difference between this way of defining a function and the way you have already seen?
function someFunction () {
// do something
}
Actually, there isn't much of a difference. The main thing is that by defining a function in the
traditional way (not using a variable), the function doesn't have to be defined before it can be used.
When the browser interprets a JavaScript file, it does so in two stages. In the first stage, the browser
constructs a list of functions that are available. In the second stage, the browser interprets the rest
of the script. This is necessary because in order to correctly interpret a script, the browser needs
to know which functions are available. For example, this piece of JavaScript code will run just fine,
even though the function is defined after it's called:
someFunction();
function someFunction () {
// do something
}
However, if the function is assigned to a variable, then this is only interpreted in the second stage.
And that means this piece of code will result in an error:
someFunction();
var someFunction = function () {
// do something
}
The browser will complain that the script accesses a variable someFunction that has not yet been
declared. Calling the function after it has been defined is perfectly fine:
var someFunction = function () {
// do something
}
someFunction();
Variables Composed of Multiple Values
Instead of containing a single value, a variable can also be composed of multiple values . This is
similar to what you do in a function, which groups instructions together. For example:
function mainLoop () {
canvasContext.fillStyle = "blue";
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
update();
draw();
window.setTimeout(mainLoop, 1000 / 60);
}
 
Search WWH ::




Custom Search