Game Development Reference
In-Depth Information
Note The phrase “all your base are belong to us” comes from the opening cut-scene of the video game
Zero Wing (1991, Sega Mega Drive) as a poor translation of the original Japanese version. Since then, the
phrase has appeared in my articles, television series, movies, websites, and books (such as this one!).
An interpreter can check the syntax of a program: any program that violates the rules is rejected.
Unfortunately, an interpreter can't check whether the semantics of the program correspond to what
the programmer had in mind. So if a program is syntactically correct, this is no guarantee that it's
semantically correct. But if it isn't even syntactically correct, it can't run at all. Syntax diagrams help
you to visualize the rules of a programming language such as JavaScript. For example, Figure 2-2 is
a simplified syntax diagram that shows how to define a function in JavaScript.
function expression
function
name
(
parameter
)
,
{
instruction
}
Figure 2-2. The syntax diagram for a function expression
You can use syntax diagrams to construct JavaScript code by starting at the top left of the diagram,
in this case at the word function , and following the arrows. When you reach the gray dot, your piece
of code is complete. Here you can clearly see that a function definition starts with the function
keyword; then you write the name of the function. After that, you write parentheses. Between these
parentheses, you can (optionally) write any number of parameters , separated by commas. Next you
write a number of instructions, all between braces. After that, you're done because you've reached
the gray dot. Throughout this topic, I use syntax diagrams to show how to structure your code
according to the syntactical rules of the JavaScript language.
Calling a Function
When the instruction canvasContext.fillRect(0, 0, canvas.width, canvas.height); is executed,
you call the fillRect function. In other words, you want the program to execute the instructions
grouped in the function fillRect . This group of instructions does exactly what you need for this
example: namely, filling a rectangle with a color. However, you need to give some extra information
to this function, because it needs to know the size of the rectangle that should be filled. The
parameters provide this extra information. A function can have more than one parameter, as you saw
in the syntax diagram. When a function is called, you always write parentheses behind it, and within
the parentheses are the parameters (if required).
 
 
Search WWH ::




Custom Search