Cover | Table of Contents | Colophon
if statement,
the while loop, and the
&& operator. The similarity
ends with this syntactic resemblance, however.
JavaScript
is an untyped language, which means that variables do not need to
have a type specified.
Objects in
JavaScript are more like
Perl's associative arrays than they
are like structures in C or objects in C++ or Java. The
object-oriented
inheritance mechanism of JavaScript is like those of the little-known
languages Self and NewtonScript; it is quite different from
inheritance in C++ and Java. Like Perl, JavaScript is an interpreted
language, and it draws inspiration from Perl in a number of places,
such as its regular expression and array-handling features.
http://www.ecma.ch) has
published three versions of the
ECMA-262 standard that standardize
the JavaScript language under the awkward name
"ECMAScript."
|
Version
|
Description
|
|---|---|
|
JavaScript 1.0
|
The original version of the language. It was buggy and is now
essentially obsolete. Implemented by Netscape 2.
|
|
JavaScript 1.1
|
Introduced a true Array object; most serious bugs resolved.
Implemented by Netscape 3.
|
|
JavaScript 1.2
|
Introduced the
switch statement, regular
expressions, and a number of other features. Almost compliant with
ECMA v1, but has some incompatibilities. Implemented by Netscape 4.
|
|
JavaScript 1.3
|
Fixed incompatibilities of JavaScript 1.2. Compliant with ECMA v1.
Implemented by Netscape 4.5.
|
|
JavaScript 1.4
|
Implemented only in Netscape server products. |
http://www.mozilla.org/js/).
Mozilla actually provides two different versions of the JavaScript
1.5 interpreter. One is written in
C and is called
"SpiderMonkey." The other is written in
Java and,
in a flattering reference to this book, is called
"Rhino."
<html>
<body>
<head><title>Factorials</title></head>
<script language="JavaScript">
document.write("<h2>Table of Factorials</h2>");
for(i = 1, fact = 1; i < 10; i++, fact *= i) {
document.write(i + "! = " + fact);
document.write("<br>");
}
</script>
</body>
</html>
<script> and
</script> tags are used to embed JavaScript
code within an
HTML file.
We'll learn more about the <script>
tag in Chapter 12.
The main feature of JavaScript
demonstrated by this example is the use of the
document.write( ) method. This method is used to dynamically output
HTML text that is parsed and displayed by the web browser;
we'll encounter it many more times in this book.
write(
) method, which we have already seen, allows you to write
arbitrary HTML into a document as the document is being parsed by the
browser. For example, you can include the current date and time in a
document or display different content on different platforms.
onchange
or onclick
event handlers. The web browser
triggers these event handlers when the user changes the input or
clicks on the Compute button
displayed in the form. Note that in each case, the value of the event
handler attribute is a string of JavaScript code: calculate(
)
. When the event handler is triggered,
it executes this code, which causes it to call the function
calculate( ).
calculate( ) function is defined in the second
half of the example, inside <script> tags.
The function reads the user's input from the form, does the
math required to compute the loan payments, and displays the results
of these calculations using the bottom three form elements.
<script>
document.write("<h2>Table of Fibonacci Numbers</h2>");
for (i=0, j=1, k=0, fib =0; i<50; i++, fib=j+k, j=k, k=fib){
document.write("Fibonacci (" + i + ") = " + fib);
document.write("<br>");
}
</script>
file: URL. Note that the
code uses the document.write(
)
method to display its HTML
output, so that you can see the results of
its computations. This is an important technique for experimenting
with JavaScript. As an alternative, you can also use the
alert( ) method to display plain-text output in a
dialog box:
alert("Fibonacci (" + i + ") = " + fib);
<html>,
<head>, and <body>
tags in your HTML file.
javascript:
URL pseudoprotocol to evaluate a JavaScript expression and return the
result. A JavaScript URL consists of the
while keyword, for
example, must be typed "while", not "While"
or "WHILE". Similarly, online,
Online, OnLine, and
ONLINE are four distinct variable names.
onclick event handler attribute is commonly
specified as onClick in HTML, but it must be
referred to as onclick in JavaScript code.
123 is a single numeric token, but
12
3 is two separate tokens
(and constitutes a syntax error, incidentally).
;), just as they
are in C, C++, and Java. The semicolon serves to separate statements
from each other. In JavaScript, however, you may omit the semicolon
if each of your statements is placed on a separate line. For example,
the following code could be written without semicolons:
a = 3; b = 4;
a = 3; b = 4;
return
,
break, and continue statements
(which are described in Chapter 6). For example,
consider the following:
return true;
return; true;
return true;
break outerloop;
break
keyword, causing a syntax error when it tries to interpret the next
line. For similar reasons, the
++
and -- postfix
operators (see Chapter 5) must always appear on
the same line as the expressions to which they are applied.
//
and the end of a line is treated as a comment and is ignored by
JavaScript. Any text between the characters
/*
and */ is also
treated as a comment. These C-style comments may span multiple lines
but may not be nested. The following lines of code are all legal
JavaScript comments:
// This is a single-line comment. /* This is also a comment */ // and here is another comment. /* * This is yet another comment. * It has multiple lines. */
12 // The number twelve 1.2 // The number one point two "hello world" // A string of text 'Hi' // Another string true // A boolean value false // The other boolean value /javascript/gi // A "regular expression" literal (for pattern matching) null // Absence of an object
{ x:1, y:2 } // An object initializer
[1,2,3,4,5] // An array initializer
_), or a dollar sign
($). Subsequent characters may be any letter or digit or an
underscore or dollar sign. (Numbers are not allowed as the first
character so that JavaScript can easily distinguish identifiers from
numbers.) These are all legal
identifiers:
i my_variable_name v13 _dummy $str
\u followed by 4 hexadecimal
digits that specify a 16-bit character encoding. For example, the
identifier π could also be written as \u03c0.
Although this is an awkward syntax, it makes it possible to translate
JavaScript programs that contain Unicode characters into a form that
allows them to be manipulated with text editors and other tools that
do not support the full Unicode character set.
break
|
do
|
if
|
switch
|
typeof
|
case
|
else
|
in
|
this
|
var
|
catch
|
false
|
0 3 10000000
char, like C, C++, and
Java do. To represent a single character, you simply use a string
that has a length of 1.
' or "). Double-quote
characters may be contained within strings delimited by single-quote
characters, and single-quote characters may be contained within
strings delimited by double quotes. String literals must be written
on a single line; they may not be broken across two lines. If you
need to include a newline character in a string literal, use the
character sequence \n
, which is documented in the next
section. Examples of string literals are:
"" // The empty string: it has zero characters 'testing' "3.14" 'name="myform"' "Wouldn't you prefer O'Reilly's book?" "This string\nhas two lines" "pi is the ratio of a circle's circumference to its diameter"
true and
false. A boolean value represents a truth
value -- it says whether something is true or not.
a == 4
a is equal to the number 4. If
it is, the result of this comparison is the boolean value
true. If a is not equal to
4, the result of the comparison is
false.
if/else
statement in JavaScript performs one
action if a boolean value is true and another
action if the value is false. You usually combine
a comparison that creates a boolean value directly with a statement
that uses it. The result looks like this:
if (a == 4) b = b + 1; else a = a + 1;
a equals 4.
If so, it adds 1 to b;
otherwise, it adds 1 to a.
true and false, it is sometimes
convenient to think of them as on
(true) and off
(false) or yes
(true) and no
(false). Sometimes it is even useful to consider
them equivalent to 1 (true) and
0 (false). (In fact, JavaScript
does just this and converts true and
false to 1 and
0 when necessary.)
Math.sin( ) function that computes the sine of an
angle.
function square(x) // The function is named square. It expects one argument, x.
{ // The body of the function begins here.
return x*x; // The function squares its argument and returns that value.
} // The function ends here.
y = Math.sin(x); y = square(x); d = compute_distance(x1, y1, z1, x2, y2, z2); move( );
image
has properties named
width and height, we can refer
to those properties like this:
image.width image.height
document.myform.button
button property of an
object that is itself stored in the myform
property of an object named document.
. syntax to extract the function value from the
object, and then use the ( ) syntax to invoke that
function. For example, to invoke the write( )
method of the Document object, you can use code like this:
document.write("this is a test");
image
object mentioned previously with
code like this:
image["width"] image["height"]
a, and i is a non-negative
integer, a[i] is an element of the array. Array
indexes begin with zero. Thus, a[2] refers to the
third element of the array a.
document.images[1].width
width
property of an object stored in the second element of an array stored
in the images property of the
document object.
Array(
)
constructor function. Once created,
any number of indexed elements can easily be assigned to the array:
var a = new Array( );
a[0] = 1.2;
a[1] = "JavaScript";
a[2] = true;
a[3] = { x:1, y:3 };
Array( )
constructor. Thus, the previous array-creation and -initialization
code could also be written:
var a = new Array(1.2, "JavaScript", true, { x:1, y:3 }); null is a special value that indicates no value.
null is usually considered to be a special value
of object type -- a value that represents no object.
null is a unique value, distinct from all other
values. When a variable holds the value
null, you know that it does not contain a valid
object, array, number, string, or boolean value.
undefined value returned when you use either a
variable that has been declared but
never had a value assigned to it, or an object
property
that does not exist. Note that this special
undefined value is not the same as
null.
null and the undefined
value are distinct, the ==
equality operator considers them to
be equal to one another. Consider the following:
my.prop == null
true either if the
my.prop property does not exist or if it does
exist but contains the value null. Since both
null and the undefined value
indicate an absence of value, this equality is often what we want.
However, if you truly must distinguish between a
null value and an undefined
value, use the ===
identity operator or the
typeof operator (see Chapter 5
for details).
null, undefined is not a
reserved word in JavaScript. The ECMAScript v3 standard specifies
that there is always a global
variable named undefined whose initial value is
the undefined value. Thus, in a conforming
implementation, you can treat
undefined
as a keyword, as long as you don't assign a value to the
variable.
undefined variable, you can simply declare your
own:
var undefined;
undefined value. The
void
operator (see Chapter 5) provides another way to obtain the
undefined value.