Writing JavaScripts |
A Brief Background of JavaScript Chapter SevenWriting JavaScriptsToday you will learn JavaScript. You have already
encountered JavaScript in a couple of the examples you've done this week. You implemented
JavaScript by hand-coding directly on the HTML page (covered on Chapter
2, "HTML and Scripting"), and by using the three editing tools you looked at
on Chapter 4, "Tools of the Trade": Word, HoTMetaL, and
the ActiveX Control Pad. JavaScript was also used in the last example on Chapter 5, "Programming for Internet Explorer," when you
looked at programming inside the Internet Explorer. Today, after looking briefly at the
background of JavaScript, you will learn all you need to know about the language, from
variables to objects. By the end of the day you will have examined dozens of examples, and
will be ready to use JavaScript in a project. A Brief Background of JavaScript
JavaScript started life as LiveScript, a scripting
language built specifically for Netscape Navigator. Netscape, in conjunction with Sun,
changed the name to JavaScript. Microsofts Internet Explorer also supports
JavaScript. JavaScript is object oriented. The Window object you learned about on Chapter 5 is a native part of JavaScript. Because it is at home with
objects, JavaScript can be used to manipulate ActiveX controls as well as the objects
native to HTML. It is important to note that JavaScript is not Java. They are similar, but
JavaScript is dedicated to Web-page scripting, whereas Java is becoming a full-blown
application builder like C or C++. JavaScript's commitment to HTML and support for ActiveX
controls makes learning JavaScript well worth your while. Overview of Scripting Architecture
To learn JavaScript, you need to know about the
following topics:
You'll be quizzed at the end of the chapter, so pay
attention! Supported Software Platforms
As of this writing, the two major Web browsers
support JavaScript. Anything you learn about JavaScript is applicable to programming on
both the Netscape Navigator and the Internet Explorer. You can find Netscape Navigator at http://www.netscape.com/.Find the Internet Explorer at
http://www.microsoft.com/ie/ie.asp. Both
are in their third version. Internet Explorer is freeware, and Netscape Navigator is
available for a nominal cost on a subscription basis. Netscape controls the JavaScript standard, and it
looks like it will remain proprietary. This is not necessarily bad. Proprietary standards
evolve faster and are less compromised than languages controlled by the more democratic
open standard approach. Because JavaScript and ActiveX are currently
supported on the Internet Explorer, the bottom line is that if you need to use JavaScript
and ActiveX right now, use the Internet Explorer as your target software platform. The JavaScript Programming Model
JavaScript is an object-oriented language. To those
of you new to programming, an object-oriented language uses objects to group
related properties and methods. You have already been introduced to one of the main
JavaScript objects, Window (discussed in detail on Chapter 5). The
Window object is a good example of how objects are constructed and used. The concepts of
subroutines and functions that you learned on Chapter 6 also apply
to JavaScript. JavaScript and object-oriented languages in general
are strong in the areas of organization and code maintenance. The downside of
object-oriented languages is that they have a steeper learning curve than procedural
languages. Design and maintenance are what recommend JavaScript to Web programmers. After
you have used an object-oriented approach for a while, you will find it well-suited to the
world of Windows and ActiveX. Language Structure
Now you can get to know JavaScript. I'll start with
a discussion of the general elements of the language, and when I'm through, you will have
covered every keyword in JavaScript. Most of the examples in this chapter are run from
within the framework of template.asp, shown in Listing 7.1. Listing 7.1. template.asp.
You have covered all the elements of this Web page
during the previous days of the week. As you can see, there are two <SCRIPT>
sections to handle two Window object events. One area is assigned to the onLoad event,
which causes the code placed in this section to be run whenever the page is loaded. The
second <SCRIPT> section is assigned to the onUnload event, and is fired every time
you leave the page. Are you ready? Time to learn a new language! GeneralJavaScript is case sensitive. This means, for
example, that the variable A is different from the variable a. Try the following in the
template:
As you would expect, given that JavaScript is case
sensitive, the output from the preceding code is The next question is, "How do I differentiate
one line from another?" In JavaScript, all you have to do is start a new line. Look
at this code:
Notice that the lines have no visible terminator.
Some languages, such as C, use a semicolon (;) as the terminator for a line. Lines of code
in JavaScript use the line feed at the end of the line as a terminator. If you feel the need to pack several lines of code
on one line, use the ; to separate them, as shown in Listing 7.2. Listing 7.2. separate.asp.
Notice how the semicolon is used in template.asp.
Running this program will produce the number 3. It will also annoy any programming purists
with whom you work. I recommend that you keep to one statement per line (unless, of
course, your goal is to annoy those who read your code). This is the only example I will show you using the
entire template. In the rest of the chapter you'll focus on the code inside. Indentation is not required to make the language
work. For example, Listing 7.3 runs identically to Listing 7.4. Listing 7.3. Indented code.
Listing 7.4. Unindented code.
Listing 7.4 runs in the same way as Listing 7.3, but
Listing 7.4 won't win you many points for style. I recommend that you use indentation to
organize your code so that if you have to go back and maintain it (or someone else does),
it is easier to understand. You will see examples of indentation used for clarity
throughout this chapter. CommentsComments can make your life, or the life of
someone who looks at your work later, much easier. Comments are not required in
JavaScript, but if you want them in your code, you have two choices: // and /* */. With
//, any characters from the start of the remark to the end of the line are ignored when
the script is run. With /* */, everything between /* and */ is ignored. An example of both
kinds of comments follows:
VariablesVariables are those things you learned in
high school algebrayou remember, the class you knew would never apply to your
"real" life. Well, you were wrong (sorry, Mr. White). Without variables,
computer languages could do little more than power player pianos or music boxes. Variables
are what allowed you to send people to the moon, build addictive games like Doom, and make
interactive Web pages. JavaScript has a simple approach to variables. Types of VariablesJavaScript supports four variable types: numeric,
string, boolean, and null. Numeric variables represent integers or floating-point numbers.
Strings are arrays of characters, such as Hello World and Good Bye. For example, the
following code sets string1 to hold the string variable hello world and mynum1 to hold the
number 4: JavaScript is loosely typed, which means that
you can turn around and assign these variables like this without the interpreter complaining. The advantage
of a loosely typed language is that you don't have to remember lots of conversion
functions. The disadvantage is that you are at the mercy of the language interpreter: it
will determine what conversions need to be conducted and how. You will need to keep an eye
on these automatic conversions. You might not always want what the interpreter gives you.
Later today I will cover conversion functions in JavaScript that provide the capability to
precisely change one type to another. The boolean variable can be either true or false.
JavaScript does not assign numbers to true and false like some other languages do. The null variable represents a variable that has not
been defined. It is not the same as a zero-length string. For example, the following code
returns the value MyUninited is null:
Now you should know the difference between a null
value and a zero-length string. Variable Naming
Names of JavaScript variables must have the
following two characteristics:
This means a variable like 22street would return an
error like the one shown in Figure 7.1. Figure 7.1. Results of an
improper variable. The error shown in the figure was generated by the
following code:
varDeclaring variables is easy, and optional, in
JavaScript. Declaring a variable is done using the key word var. Consider the following
code:
Notice how value1 is declared using var, and value2
is not declared. The form will produce these lines: You can also declare a variable without assigning it
a value, but you cannot have an undeclared variable without an assigned value. The
interpreter doesnt initialize undeclared variables. Look at the following
modification to the previous code:
This causes the following error: Optional declaration, bypassing the use of var is
fine, but it will not sit well with programming purists. Also, you might be working in a
corporation whose programming standards require that all variables to be declared. Uninitialized VariablesIf you use var to declare a variable and then print
that variable, what will be in it? I have spent days in other languages tracking down bugs
caused by uninitialized variables assigned some random number. JavaScript does not support
this kind of frustration. Variables in JavaScript are given a value of null when they are
declared without being assigned in the var statement. You saw an example of this when you
looked at the null value in the "Types of Variables" section of this chapter. Constant VariablesIn general, JavaScript does not support constant
variables. A constant variable is one of those programming oxymorons that means a
variable that cannot be changed after it is declared. A constant variable is used to hold
things that should not be open to the interpretation of the programmer (like the value of
pi, for instance). This prevents the programmer from improving pi or accidentally changing
pi. Any variable you declare in JavaScript can be
modified. If you want to implement constants in your Web pages, you must give them a
unique identifier (I recommend all uppercase lettersit is the C programmer in me)
and invent a stiff penalty for programmers who change them during the course of a program
(I recommend reassignment as the tech writer for a group of assembly language
programmersthey hate that). Some objects within the JavaScript environment have
read-only properties that can be used as constant variables. For example, the Math object,
discussed later, has a property named PI, which is shown in the following code:
This code produces the constant Any attempt to change the value of Math.PI is
ignored, as in the following modification to the code:
This code still produces constant 3.14159265358979. The bottom line here is that although there are
built-in constants, the programmer cannot create a new constant. Variable Scope and Global VariablesThe scope of a variable has to do with where
it is visible. The code in Listing 7.5 shows you how scope works. Listing 7.5. scope01.asp.
The code in Listing 7.5 produces the following
output:
Notice that the MyVariable declared outside of the
functions is visible to all functions within the <SCRIPT> tags, making it global.
Then, when a variable is declared inside ThingOne with the same name, that local variable
is used inside procedure ThingOne. Just to prove that the global MyVariable isn't
overwritten, ThingTwo writes out its value so you can see that the global MyVariable
hasn't changed. Also of note here is how the Window object is global. Now change the code so that ThingOne and ThingTwo
are in a different <SCRIPT> tag (see Listing 7.6). Listing 7.6. scope02.asp
Run the page. The results are identical. Now you've
seen that scope applies across <SCRIPT> sections. ProceduresIn general, a procedure contains programming
instructions, and can be assigned to events or called from other functions. You have seen
procedures in every example today. JavaScript has only one kind of procedure: the
function. Let's see how it works. FunctionsA function has this general structure: function MyFunction(arg2, arg2) { //Lines of code } The keyword function lets the interpreter know that
what follows is a function. After the keyword function is the function name, followed by
any arguments the function has enclosed in parentheses (()). The function is given copies
of the arguments, which means that the function cannot change the original value of an
argument. A function can also return a value using the keyword
return. Type the code found in Listing 7.7 (sub01.asp on the CD-ROM). Listing 7.7. sub01.asp
This is a simple radians-to-degrees function. It
returns the following value: JavaScript has three built-in functions: eval,
parseInt, and parseFloat. The rest of the functionality in JavaScript is contained in
objects, which you will learn about later today in the section called
"Objects.". For now, let's look at the functions. evaleval has this syntax: eval takes the string argument and acts like a mini
interpreter. For example, the following code returns the value 11730.
Note how the code is in the <BODY> section of
the form. If this code is run in the onLoad event, it returns the string (345*34) instead
of its value. parseInt and parseFloatThe functions parseInt and parseFloat both take a
single argument: a string. The function parseInt takes the string and attempts to return
an integer. The function parseFloat takes the string and attempts to return a float value.
Both functions are demonstrated in Listing 7.8, parse.asp. Listing 7.8. parse.asp.
Listing 7.8 returns the following: Before you go any further, let's look at the
operators you use to string your variables and functions together. OperatorsOperators determine what is done to variables
and functions. There are five types of operators: assignment, arithmetic, logical,
comparison, and string. Lets start with the most usedassignment operators. AssignmentsYou use assignment operators all the time to assign
one value to another; indeed, assignment variables are the heart of programming.
JavaScript not only has the traditional =, but also includes five others: +=, -=, *=, /=,
and %=. They are explained in Table 7.1 Table 7.1. Assignment operators.
Listing 7.9 uses all of the assignment operators
shown in Table 7.1. Listing 7.9. assign.asp
Note how the numbers are reloaded between prints.
This is necessary because MyNum1 is reassigned in every writeln. Listing 7.9 produces the
following output: Arithmetic
The math functions are another group you tend to
take for granted. The important thing to note as you go through these operators is how
they work on various combinations of integers and real numbers. Table 7.2 shows the
arithmetic operators. Table 7.2. Arithmetic operators.
Listing 7.10 contains examples of the primary
arithmetic operators: Listing 7.10. asgmath.asp.
The following illustrates how these arithmetic
operators work with various combinations of float and int. Increment (++) and decrement(--) operators are old
hat to C programmers. Listing 7.11 shows how these two features work. Listing 7.11. asginc.asp.
Displaying the page described in Listing 7.11
produces the following result: The first two numbers, 33 (32++)
and 31 (32--) are easy to understand. The last three are more difficult. Variable a is
originally 5, so after two increments it becomes 7, which explains the first number. The
second equation (b = ++a) causes a to change from 5 to 6 and for 6 to be assigned to b,
which explains the second number. The equation c = a++ results in a, which starts as 6, to
be assigned to c before it is incremented, leaving c at 6 and a at 7. Be careful when
using increments and decrements with an assignment statement. Logical OperatorsLogical operators are used to combine the
results of two boolean expressions. They are described in Table 7.3. Table 7.3. Logical operators.
Listing 7.12 shows these logical operators at work. Listing 7.12. logops.asp.
Listing 7.12 returns the following value where 0 is
false and -1 is true: Comparison OperatorsComparison operators are used inside JavaScript's
control structures to test the relationship between variables. They are described in Table
7.4. Table 7.4. Comparison operators.
The only unusual thing here (if you are not a C
programmer) is the == operator (test for equality). In JavaScript, == always makes a
comparison, and = always makes an assignment. Don't confuse the two. The statement if (a =
5) will ruin your whole day if you are trying to compare a and 5 rather than assign a to
5. Look for examples in the section found later in this chapter called Program Flow. String OperatorsThere is only one string operator: concatenation
(+). It's funny that a language that uses an = and an == to give the programmer greater
flexibly would also use the + to add numbers and concatenate strings. Listing 7.13 shows
string operators at work. Listing 7.13. strop.asp
Notice that when the number is combined with the
strings, the number is automatically converted to a string, as shown in the result of
running strop.asp: Operator PrecedenceYou have seen that it is possible to combine several
comparison operators from the arithmetic, comparison, and logical groups on one line. You
have also seen that the operators can be grouped within parentheses to clarify the order
of operation. When expressions are not grouped within (), what happens? The following
order is used:
Listing 7.14 is illustrates arithmetic precedence. Listing 7.14. prec.asp
Listing 7.14 results in the following: Quite a difference. Maybe this is what is happening
to my paycheck. Make a note to talk to payroll. My advice here is use () to group your
statements so they are performed in the order you want and not in the order the machine
wants. ObjectsAt the beginning of the day you saw that JavaScript
is an object-oriented language. This means that you can create objects that have their own
properties and methods, just like the Windows object. This allows you to group methods and
properties logically. For example, the document object has properties, such as forms (an
array of forms on the document) and methods like writeln that relate to documents. In
JavaScript, it is easy for you to create your own objects. Creating an ObjectCreating an object uses the same syntax as creating
a function. The following code creates a template for an object:
To create a function with this template, use the new
keyword, as shown in the following code:
The line new MyObject("Circle",10,25)
creates the new object that runs the template you created, assigns the variables in the
argument list, and names the new object Shape1. The output from the code verifies that the
following variables were set: PropertiesThese variables you set are the properties of your
object. They can be accessed by the same notation you used with the Document object. For
example, the type in your Shape1 object can be referenced by Shape1.type, as you did in
the following line: Properties can include other objects. Look at the
Listing 7.15, object02.asp, and notice the modifications to MyObject, which you created in
the section titled "Creating an Object." Listing 7.15. object02.asp
Notice how you added a new property, pos, of the
type position, to store the x and y values of MyObject. This new property is accessed
through the notation Shape.pos.x. The result of this page shows that the properties did
make it into Shape1: MethodsWhat if you want to make your object a little more
self-sufficient by adding some methods? Listing 7.16 illustrates how to make your object
print itself out. Listing 7.16. object03.asp.
Here you have moved the printing to its own method,
Printout. Inside Printout you used the this keyword to designate the internal properties
of MyObject. If you tried to run the method, Printout, as a standalone function, you would
get error centering on the nonexistence of the variables. The magic happens with the
following line, which is found inside MyObject: This line designates Printout as a method of
MyObject, and grants Printout access to the properties of MyObject. Calling Shape1.printme
results in the following: Associative ArraysInternally, the data contained in an object is
contained in an associative array. This allows you to associate a value from the
object with the property name, as shown in Listing 7.17. Listing 7.17 object04.asp.
In this example, you used Shape1.["type"]
to access the Shape1.type property. The results are as shown. ArraysThose of you with a programming background are used
to working with arrays. For those of you new to programming, an array is a
collection of elements that can be accessed by an index. For example, MyArray[1] would
access the element in the array with an index of one. JavaScript does not have built-in support for
arrays. If you need to use arrays, you will have to build your own. Don't panic, it isn't
hard to do. Here are two ways to hand-build an array. The first array you will build will allow you to
enter elements into the array when you first declare it. Listing 7.18 shows this method. Listing 7.18. array01.asp. Note that arguments are used both to find out how
many arguments there are (initArray.arguments.length), and as an array of those arguments
(arguments[I]). The output from this example looks like the following: Another way to create an array is shown in Listing
7.19. Listing 7.19. array02.asp.
In this listing, you can size the array and
initialize it when you declare it. The output shows both the initial values (MyArray[4])
and the values you set after the array was declared: This lack of a built-in array behavior is
inconvenient but, on the plus side, you can create your arrays that fit into the problems
you solve with JavaScript. Built-In ObjectsJavaScript contains both user-built objects, which
you have already covered, and built-in objects. You have already used the Window object;
the three remaining built-in objects are String, Math, and Date. The String ObjectThe JavaScript String object has one property and
nineteen methods. You create a string whenever you assign a string to a variable. The
following lines result in a string object with full rights to the property and functions
described in Table 7.5 and Table 7.6:
Table 7.5. String object
(properties).
Table 7.6. String object
(methods).
Listing 7.20 shows how the string manipulation
functions work. Listing 7.20 string01.asp.
The Math ObjectThe JavaScript Math object has six properties and
seventeen methods. Math functions are referenced using the object Math, as it Math.PI. The
properties and functions of the Math object are described in Table 7.7 and Table 7.8. Table 7.7. Math object
(properties).
Table 7.8. Math object (methods).
Listing 7.21 gives you a general idea about how to
use these functions. Listing 7.21. math.asp.
Notice how the with keyword is used. Inside the
brackets of the with (Math) statement, the Math object is assumed and doesn't have to be
typed. The output is as follows:
The Date ObjectThe JavaScript Date object has zero properties and
twenty methods. Define a new Date variable with the syntax: where dateinfo is an optional indicator of the date format that can have one of three formats:
The methods that go with the Date object appear in
Table 7.9. Table 7.9. The Date object.
Listing 7.22 shows how these functions can be used. Listing 7.22 date.asp.
Program FlowJavaScript has four control structures: if, for,
while, and for...in. if, for and while apply to general coding, and for...in is used to
iterate through objects. Lets look at the general control structures first. ifYou have already used this function close to a
hundred times this week, but not many in JavaScript. The general syntax is:
Listing 7.23 illustrates the if function. Listing 7.23. flow01.asp.
The result of this page is as follows: Notice how you embedded a second if statement inside
the else clause of the first if statement. I have seen this kind of construction
used to decode a user choice, and it is your only option in JavaScript because there is
not a switch clause or a select case clause. forThis function allows you to perform selected program
statements a given number of times. The syntax is:
The initial expression usually declares an index
variable that is checked against the condition and incremented (or decremented) in the
last section. Listing 7.24 provides an example. Listing 7.24. flow02.asp.
Listing 7.24 produces the following: Notice how the string method charAt90 was used to
read the characters. whileThe while statement allows you to loop through code
until a condition is met. The condition is tested before the loop is entered. The syntax
is: Listing 7.25 provides an example of the while
statement. Listing 7.25. flow03.asp.
for...inThe for...in statement is called an iterater.
An iterater cycles through all the things in a collection. The forin statement in
JavaScript cycles through all the members of an object. The syntax is: Aim the result of Listing 7.26 at the object you
created in object04.asp (Listing 7.17). Listing 7.26. flow04.asp.
Here you used the iterater to cycle through Shape1
and assign its members to Shape2, a function not uncommon in the object-oriented world. User Interface ElementsJavaScript has three user interface elements (other
than the input controls native to HTML) that you have already seen: The alert, prompt and
confirm boxes. Given that you have ActiveX to create the main screen elements, these three
functions serve to display common user input dialogs. The syntax for alert is where message is optional and evaluates to a
printable value. The prompt box, with the following syntax, is a
little more complex: where message has the same characteristics as
alert's message, and the optional default is a default value for the text box on the
prompt. The confirm box has the same syntax as alert: except confirm returns a distinct value for each of
its two buttons (OK and Cancel). See Listing 7.27 for a demonstration of these
controls. Listing 7.27. visual.asp.
This function keeps putting up prompt dialogs as
long as you choose OK in the confirm dialog. When you choose Cancel in the confirm dialog,
the last alert shows the last number picked. SummaryIt was a long day, but worthwhile. You looked at
JavaScript from variables to objects, and all the stops in between. This is the final
stone in your language foundation (until the next new scripting language comes along).
Later in the guide there is a chapter where you can use these tools to build a Web site
using ActiveX and JavaScript. If you skipped the VBScript pages (Day 6),
I strongly urge you to go back and at least skim them. VBScript has some features you
might find interesting, such as error-catching and a switch-statement features. Q&A
var ROSE Rose = 1 ROSE = ROse + 4 ROse = Rose + ROSE document.open() document.writeln("<PRE>") document.writeln(Rose) document.writeln(ROSE) document.writeln(ROse) document.writeln("</PRE>") document.close() -->.
WorkshopAdd a copy method to Object04.asp that allows the
user to copy the contents of another like object(hint: see flow04). Quiz
What control structure can I use to get information out of my home-made object?
|