Game Development Reference
In-Depth Information
The number passed as a parameter would simply be converted to text. In this case, of course, there
is no canvas with ID 12, so the program would no longer correctly. But if you were to replace the
canvas ID as follows, then the program would work just fine:
<canvas id="12" width="800" height="480"></canvas>
The browser automatically converts between text and numbers.
Most programming languages are a lot stricter than JavaScript. In languages such as Java and C#,
conversion between types is done on a very limited basis. Most of the time, you have to explicitly
tell the compiler that a conversion between types needs to be done. Such a type conversion is also
called a
cast
.
What is the reason for having a stricter policy with regard to type conversions? For one thing,
clearly defining which type a function or method expects as a parameter makes it easier for other
programmers to understand how to use the function. Look at the following header for example:
function playAudio (audioFileId)
By only looking at this header, you can't be sure if
audioFileId
is a number or text. In C#, the header
of a similar method looks like this:
void playAudio(string audioFileId)
You can see that in this header, not only a name is provided, but also a
type
that belongs to this
name. The type in this case is
string
, which in C# means text (a string of characters). Furthermore,
in front of the method name is the word
void
, which means the method doesn't have a result that
can be stored (I talk more about methods/functions with results in Chapter 7).
Declaration and Assignment of Variables
It's easy to store information in JavaScript and use it later. What you need to do is provide a name
that you use when you refer to this information. This name is called a
variable
. When you want to use
a variable in your program, it's a good idea to
declare
it before you actually use it. This is how you
declare a variable:
var red;
In this example,
red
is the name of the variable. You can use the variable in your program to store
information that you need later.
When you declare a variable, you don't need to provide the type of information that you store.
A variable is simply a place in memory that has a name. Quite a few programming languages require
the type of a variable to be fixed when the variable is declared. For example, this is the case in
languages such as C++ or Java. However, many script languages (including JavaScript) allow you
to declare a variable without defining its type. When a language doesn't require a type definition for
declaring a variable, then the language has
loose typing
. In JavaScript, you can declare more than a
single variable at once. For example:
var red, green, fridge, grandMa, applePie;
Search WWH ::
Custom Search