Activex Quick Tutorial

Web based School

Writing JavaScripts


Previous Next

A Brief Background of JavaScript


Chapter Seven

Writing JavaScripts

Today 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. Microsoft’s 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:

  • Supported software platforms

  • JavaScript programming model

  • Variable types

  • Operators

  • Variable scope

  • Functions

  • Program flow

  • User interface

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.

<HTML>
<HEAD>
<TITLE>Example Template</TITLE>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
// Your Code Here
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onUnload()">
<!--
//Your Code Here
-->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

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!

General

JavaScript is case sensitive. This means, for example, that the variable A is different from the variable a. Try the following in the template:

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
// Your Code Here
var ROSE
var Rose
var ROse
Rose = 1
ROSE = 4
ROse = Rose + ROSE
document.open()
document.writeln("<PRE>")
document.writeln(Rose)
document.writeln(ROSE)
document.writeln(ROse)
document.writeln("</PRE>")
document.close()
-->
</SCRIPT>

As you would expect, given that JavaScript is case sensitive, the output from the preceding code is
1

4

5

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:

<!--function CommandButton1_Click()
{
parent.frames(1).navigate TextBox2.Text
label1.caption = parent.frames(1).location.href
}
-->
</SCRIPT>

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.

<HTML>
<HEAD>
<TITLE>Example Template</TITLE>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
// Your Code Here
var A = 0
A = A + 1 ; A = A + 1; A = A + 1
document.Open(); document.write;document.close()
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onUnload()">
<!--
//Your Code Here
-->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

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.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
// Your Code Here
var A = 0
A = A + 1
A = A + 1
A = A + 1
document.Open()
document.write
document.close()
-->
</SCRIPT>

Listing 7.4. Unindented code.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
// Your Code Here
var A = 0
A = A + 1
A = A + 1
A = A + 1
document.Open()
document.write
document.close()
-->
</SCRIPT>

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.

Comments

Comments 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:

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
// This is ignored to the end of the line
/* All of these lines
will be
ignored
*/
var A = 0
A = A + 1
A = A + 1
A = A + 1
document.Open()
document.write
document.close()
-->
</SCRIPT>

Variables

Variables are those things you learned in high school algebra—you 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 Variables

JavaScript 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:
var string1 = "hello world"
var mynum1 =

JavaScript is loosely typed, which means that you can turn around and assign these variables like this
string1 = 4
mynum1 = "hello world"

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:

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var MyUninited
var MyInit
document.Open()
MyInit = ''
if (MyInit == null)
{
document.write('MyInit is null')
}
if (MyUninited == null)
{
document.write('MyUninited is null')
}
document.close()
-->
</SCRIPT>

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:

  • They must begin with an alphabetic character or an underscore(_)

  • They must be unique in the scope in which they are declared. You can’t have two MyVars in a function.

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:

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var 22street = 0
document.Open()
document.write(22street)
document.close()
-->
</SCRIPT>
var

Declaring variables is easy, and optional, in JavaScript. Declaring a variable is done using the key word var. Consider the following code:

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var value1 = 1
value2 = 'value two'
document.Open()
document.writeln('<PRE>')
document.writeln(value1)
document.writeln(value2)
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

Notice how value1 is declared using var, and value2 is not declared. The form will produce these lines:

1

value two

You can also declare a variable without assigning it a value, but you cannot have an undeclared variable without an assigned value. The interpreter doesn’t initialize undeclared variables. Look at the following modification to the previous code:

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var value1
value2
document.Open()
document.writeln('<PRE>')
document.writeln(value1)
document.writeln(value2)
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

This causes the following error:
Microsoft JScript runtime error
[Line: 7] 'value2' is undefined

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 Variables

If 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 Variables

In 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 letters—it 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 programmers—they 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:

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
document.Open()
document.writeln('<PRE>')
document.writeln(Math.PI)
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

This code produces the constant

3.14159265358979

Any attempt to change the value of Math.PI is ignored, as in the following modification to the code:

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
Math.PI = 6
document.Open()
document.writeln('<PRE>')
document.writeln(Math.PI)
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

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 Variables

The 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.

<SCRIPT LANGUAGE="JavaScript">
<!--
//Global Variable
var MyVariable = "Global edition of My Variable"
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
window.document.open()
window.document.writeln("<PRE>")
window.document.write("In onLoad MyVariable is ")
window.document.writeln(MyVariable)
ThingOne()
ThingTwo()
window.document.writeln("</PRE>")
window.document.close()
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
function ThingOne()
{
var MyVariable
MyVariable = "ThingOne edition of MyVariable"
window.document.write("In ThingOne MyVariable is ")
window.document.writeln(MyVariable)
}
function ThingTwo()
{
window.document.write("In ThingTwo MyVariable is ")
window.document.writeln(MyVariable)
}
-->
</SCRIPT>

The code in Listing 7.5 produces the following output:

In onLoad MyVariable is Global edition of My Variable
In ThingOne MyVariable is ThingOne edition of MyVariable
In ThingTwo MyVariable is Global edition of My Variable

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

<HTML>
<HEAD>
<TITLE>Example Template</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
//Global Variable
var MyVariable = "Global edition of My Variable"
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
window.document.open()
window.document.writeln("<PRE>")
window.document.write("In onLoad MyVariable is ")
window.document.writeln(MyVariable)
ThingOne()
ThingTwo()
window.document.writeln("</PRE>")
window.document.close()
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
function ThingOne()
{
var MyVariable
MyVariable = "ThingOne edition of MyVariable"
window.document.write("In ThingOne MyVariable is ")
window.document.writeln(MyVariable)
}
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
function ThingTwo()
{
window.document.write("In ThingTwo MyVariable is ")
window.document.writeln(MyVariable)
}
-->
</SCRIPT>

Run the page. The results are identical. Now you've seen that scope applies across <SCRIPT> sections.

Procedures

In 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.

Functions

A 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

<SCRIPT LANGUAGE="JavaScript">
<!--
function RADtoDEG (Radian)
{
return Radian * 57.32
}
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var MyRadian = Math.PI/4
var MyDegree = RADtoDEG(MyRadian)
document.writeln("<PRE>")
document.writeln(MyRadian +" Rad is " + MyDegree + "degs")
document.writeln("</PRE>")
-->
</SCRIPT>

This is a simple radians-to-degrees function. It returns the following value:
0.785398163397448 Rad is 45.0190227259417degs

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.

eval

eval has this syntax:

eval(string)

eval takes the string argument and acts like a mini interpreter. For example, the following code returns the value 11730.

<BODY>
<SCRIPT LANGUAGE="JavaScript" >
<!--
var question = '345*34'
var answer = eval(question)
alert(eval(question))
document.writeln("<PRE>")
document.writeln(answer)
document.writeln("</PRE>")
-->
</SCRIPT>
</BODY>

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 parseFloat

The 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.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var MyString = "34.345"
var MyFloat = parseFloat(MyString)
var MyInt = parseInt(MyString)
document.Open()
document.writeln('<PRE>')
document.writeln('MyFloat = ' + MyFloat)
document.writeln('MyInt = '+ MyInt )
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

Listing 7.8 returns the following:
MyFloat = 34.345
MyInt = 34

Before you go any further, let's look at the operators you use to string your variables and functions together.

Operators

Operators 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 used—assignment operators.

Assignments

You 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.

Operator Definition
= Assigns value of right expression to left expression
+= Same as A = A + B
-= Same as A = A - B
*= Same as A = A * B
/= Same as A = A / B
%= Same as A = A % B (divides A and B and assigns remainder to A)

Listing 7.9 uses all of the assignment operators shown in Table 7.1.

Listing 7.9. assign.asp

???jeff: I removed caps in Assign.asp. Is that correct? -kate<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var MyNum1 = 32
var MyNum2 = 6
document.Open()
document.writeln('<PRE>')
MyNum1 = 32
MyNum2 = 6
document.writeln('MyNum1 = MyNum2 is ' + (MyNum1 = MyNum2))
MyNum1 = 32
MyNum2 = 6
document.writeln('MyNum1 += MyNum2 is ' + (MyNum1 += MyNum2))
MyNum1 = 32
MyNum2 = 6
document.writeln('MyNum1 = MyNum2 is ' + (MyNum1 -= MyNum2))
MyNum1 = 32
MyNum2 = 6
document.writeln('MyNum1 = MyNum2 is ' + (MyNum1 *= MyNum2))
MyNum1 = 32
MyNum2 = 6
document.writeln('MyNum1 = MyNum2 is ' + (MyNum1 /= MyNum2))
MyNum1 = 32
MyNum2 = 6
document.writeln('MyNum1 = MyNum2 is ' + (MyNum1 %= MyNum2))
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

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:
MyNum1 = MyNum2 is 6
MyNum1 += MyNum2 is 38
MyNum1 = MyNum2 is 26
MyNum1 = MyNum2 is 192
MyNum1 = MyNum2 is 5.33333333333333
MyNum1 = MyNum2 is 2

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.

Operator Definition
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (assigns the remainder of a division)
++ Increments number by one
-- Decrements number by one

Listing 7.10 contains examples of the primary arithmetic operators:

Listing 7.10. asgmath.asp.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var MyNum1 = 32
var MyNum2 = 6
document.Open()
document.writeln('<PRE>')
document.writeln("For Two integers, 32 and 6")
document.writeln(MyNum1 +' + '+ MyNum2 +'is' + (MyNum1 + MyNum2))
document.writeln(MyNum1 +' - '+ MyNum2 +'is' + (MyNum1 - MyNum2))
document.writeln(MyNum1 +' * '+ MyNum2 +'is' + (MyNum1 * MyNum2))
document.writeln(MyNum1 +' / '+ MyNum2 +'is' + (MyNum1 / MyNum2))
document.writeln(MyNum1 +' % '+ MyNum2 +'is' + (MyNum1 % MyNum2))
MyNum1 = 32.23
MyNum2 = 6.98
document.writeln("For Two Floats, 32.23 and 6.98")
document.writeln(MyNum1 +' + '+ MyNum2 +'is' + (MyNum1 + MyNum2))
document.writeln(MyNum1 +' - '+ MyNum2 +'is' + (MyNum1 - MyNum2))
document.writeln(MyNum1 +' * '+ MyNum2 +'is' + (MyNum1 * MyNum2))
document.writeln(MyNum1 +' / '+ MyNum2 +'is' + (MyNum1 / MyNum2))
document.writeln(MyNum1 +' % '+ MyNum2 +'is' + (MyNum1 % MyNum2))
MyNum1 = 32.23
MyNum2 = 6
document.writeln("For Float and Int, 32.23 and 6")
document.writeln(MyNum1 +' + '+ MyNum2 +'is' + (MyNum1 + MyNum2))
document.writeln(MyNum1 +' - '+ MyNum2 +'is' + (MyNum1 - MyNum2))
document.writeln(MyNum1 +' * '+ MyNum2 +'is' + (MyNum1 * MyNum2))
document.writeln(MyNum1 +' / '+ MyNum2 +'is' + (MyNum1 / MyNum2))
document.writeln(MyNum1 +' % '+ MyNum2 +'is' + (MyNum1 % MyNum2))
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

The following illustrates how these arithmetic operators work with various combinations of float and int.

???Jeff: What are "float" and "int"? -kim

For Two integers, 32 and 6

32 + 6is38

32 - 6is26

32 * 6is192

32 / 6is5.33333333333333

32 % 6is2

For Two Floats, 32.23 and 6.98

32.23 + 6.98is39.21

32.23 - 6.98is25.25

32.23 * 6.98is224.9654

32.23 / 6.98is4.61747851002865

32.23 % 6.98is4.31

For Float and Int, 32.23 and 6

32.23 + 6is38.23

32.23 - 6is26.23

32.23 * 6is193.38

32.23 / 6is5.37166666666667

32.23 % 6is2.23

Increment (++) and decrement(--) operators are old hat to C programmers. Listing 7.11 shows how these two features work.

Listing 7.11. asginc.asp.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var result1 = 32
result1++
var result2 = 32
result2--
var a = 5
b = ++a
c = a++
document.Open()
document.writeln('<PRE>')
document.writeln( result1)
document.writeln( result2)
document.writeln( a)
document.writeln( b)
document.writeln( c)
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

Displaying the page described in Listing 7.11 produces the following result:
33

31

7

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 Operators

Logical operators are used to combine the results of two boolean expressions. They are described in Table 7.3.

Table 7.3. Logical operators.

Operator Definition
&& Logical and—Returns true when both expressions are true, otherwise it returns false.
|| Logical or—Returns true if either one or both of the expressions are true. Returns false if they are both false.
! Negation—Used on only one expression. Returns true if expression is false and false if the expression is true.

Listing 7.12 shows these logical operators at work.

Listing 7.12. logops.asp.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
document.Open()
document.writeln('<PRE>')
document.writeln( false && false)
document.writeln( false && true)
document.writeln( true && true)
document.writeln( true || false)
document.writeln( false || false)
document.writeln( !false)
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

Listing 7.12 returns the following value where 0 is false and -1 is true:
0
0
-1
-1
0
-1


Comparison Operators

Comparison 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.
Operator Definition == Comparison for equality(different from assignment statement =) != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to

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 Operators

There 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

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var string1 = "Thing one "
var string2 = "and "
var string3 = "Thing two and "
var mynum = 3
document.Open()
document.writeln('<PRE>')
document.writeln(string1 + string2 + string3 + mynum)
document.writeln('</PRE>')
document.close()
-->
</SCRIPT>

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:

Thing one and Thing two and 3


Operator Precedence

You 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:

  • assignment—= += -= *= /= %= <<= >>= >>>= &= ^= |=

  • conditional—?:

  • logical-or—||

  • logical-and—&&

  • bitwise-or—|

  • bitwise-xor—^

  • bitwise-and—&

  • equality—== !=

  • relational—< <= > >=

  • bitwise shift—<< >> >>>

  • addition/subtraction—+ -

  • multiply/divide—* / %

  • negation/increment—! ~ - ++ --

Listing 7.14 is illustrates arithmetic precedence.

Listing 7.14. prec.asp

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
A = 10
B = 20
C = 30
Answer1 = A + B / C * 12
Answer2 = (A + B)/(C * 12)
//window.document.open
window.document.writeln("<PRE>")
window.document.write("A + B / C * 12 = ")
window.document.writeln(Answer1)
window.document.write("(A + B) / (C * 12) = ")
window.document.writeln(Answer2)
window.document.writeln("</PRE>")
//window.document.close
-->
</SCRIPT>

Listing 7.14 results in the following:

A + B / C * 12 = 18
(A + B) / (C * 12) = 8.33333333333333E-02

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.

Objects

At 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 Object

Creating an object uses the same syntax as creating a function. The following code creates a template for an object:


<SCRIPT LANGUAGE="JavaScript">
<!--
function MyObject(type, height, width)
{
this.type = type
this.height = height
this.width = width
}
-->
</SCRIPT>

To create a function with this template, use the new keyword, as shown in the following code:

<SCRIPT LANGUAGE="JavaScript">
<!--
function MyObject(type, height, width)
{
this.type = type
this.height = height
this.width = width
}
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
Shape1 = new MyObject("Circle", 10, 25)
window.document.open()
window.document.writeln("<PRE>")
window.document.writeln(Shape1.type)
window.document.writeln(Shape1.height)
window.document.writeln(Shape1.width)
window.document.writeln("</PRE>")
window.document.close()
-->
</SCRIPT>

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:
Circle

10

25


Properties

These 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:

window.document.writeln(Shape1.type)

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

<SCRIPT LANGUAGE="JavaScript">
<!--
function MyObject(type, height, width, x, y)
{
this.type = type
this.height = height
this.width = width
this.pos = new Position(x,y)
}
function Position(x,y)
{
this.x = x
this.y = y
}
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
Shape1 = new MyObject("Circle", 10, , 24, 167)
window.document.open()
window.document.writeln("<PRE>")
window.document.writeln(Shape1.type)
window.document.writeln(Shape1.height)
window.document.writeln(Shape1.width)
window.document.writeln(Shape1.pos.x)
window.document.writeln(Shape1.pos.y)
window.document.writeln("</PRE>")
window.document.close()
-->
</SCRIPT>

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:

Circle

10

25

24

167


Methods

What 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.

<SCRIPT LANGUAGE="JavaScript">
<!--
function MyObject(type, height, width, x, y)
{
this.type = type
this.height = height
this.width = width
this.pos = new Position(x,y)
this.printme = Printout
}
function Position(x,y)
{
this.x = x
this.y = y
}
function Printout()
{
window.document.open()
window.document.writeln("<PRE>")
window.document.writeln('type = ' + this.type)
window.document.writeln('height = ' + this.height)
window.document.writeln('width = ' + this.width)
window.document.writeln('x value= ' + this.pos.x)
window.document.writeln('y value = ' + this.pos.y)
window.document.writeln("</PRE>")
window.document.close()
}
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
Shape1 = new MyObject("Circle", 10, 25, 24, 167)
Shape1.printme()
-->
</SCRIPT>

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.printme = Printout

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:

type = Circle

height = 10

width = 25

x value= 24

y value = 167


Associative Arrays

Internally, 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.

<SCRIPT LANGUAGE="JavaScript">
<!--
function MyObject(type, height, width, x, y)
{
this.type = type
this.height = height
this.width = width
this.pos = new Position(x,y)
this.printme = Printout
}
function Position(x,y)
{
this.x = x
this.y = y
}
function Printout()
{
window.document.writeln("<PRE>")
window.document.writeln('type = ' + this.type)
window.document.writeln('height = ' + this.height)
window.document.writeln('width = ' + this.width)
window.document.writeln('x value= ' + this.pos.x)
window.document.writeln('y value = ' + this.pos.y)
window.document.writeln("</PRE>")
}
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
window.document.open()
Shape1 = new MyObject("Circle", 10, 25, 24, 167)
Shape1.printme()
Shape1["type"] = "Square"
Shape1["height"] = 42
Shape1.printme()
window.document.close()
-->
</SCRIPT>

In this example, you used Shape1.["type"] to access the Shape1.type property. The results are as shown.


type = Circle

height = 10

width = 25

x value= 24

y value = 167

type = Square

height = 42

width = 25

x value= 24

y value = 167


Arrays

Those 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.
<SCRIPT LANGUAGE="JavaScript">
<!--
function initArray()
{
this.length = initArray.arguments.length
for (var i = 0; i < this.length; i++)
this[i+1] = initArray.arguments[i]
}
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var MyArray = new initArray("Thing1", "Thing2", 3, 4)
document.writeln("<PRE>")
document.writeln("MyArray[4] = "+ MyArray[1])
document.writeln("MyArray[4] = "+ MyArray[2])
document.writeln("MyArray[4] = "+ MyArray[3])
document.writeln("MyArray[4] = "+ MyArray[4])
document.writeln("</PRE>")
-->
</SCRIPT>

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:

MyArray[1] = Thing1

MyArray[2] = Thing2

MyArray[3] = 3

MyArray[4] = 4

Another way to create an array is shown in Listing 7.19.

Listing 7.19. array02.asp.

<SCRIPT LANGUAGE="JavaScript">
<!--
function initArray (maxnumb, initValue) {
// maxnumb: how many elements in an array
// initValue: initialize the array with this value
this.length = maxnumb;
// you can start with j=0 for a zero based system
for (var j=1; j <= maxnumb; j++)
this[j] = initValue;
return this;
}
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var MyArray = new initArray(10,"*")
MyArray[1] = "This"
MyArray[2] = "and"
MyArray[3] = "That"
document.writeln("<PRE>")
document.writeln("MyArray[1] = "+ MyArray[1])
document.writeln("MyArray[2] = "+ MyArray[2])
document.writeln("MyArray[3] = "+ MyArray[3])
document.writeln("MyArray[4] = "+ MyArray[4])
document.writeln("MyArray.lenght = "+ MyArray.length)
document.writeln("</PRE>")
-->
</SCRIPT>

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:

MyArray[1] = This

MyArray[2] = 2

MyArray[3] = That

MyArray[4] = *

MyArray.lenght = 10

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 Objects

JavaScript 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 Object

The 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:

var mystring ="Hello World"

myotherstring = "Something"


Table 7.5. String object (properties).

Property Definition
length An integer containing the number of characters in the string


Table 7.6. String object (methods).

Methods Definition
anchor(name) Causes its string to behave as though it is inside an <A> section with the attribute NAME, assigned to the value of name.
Big() Causes its string to behave as though it is inside a <BIG> section.
Blink() Causes its string to behave as though it is inside a <BLINK> section.
Bold() Causes its string to behave as though it is inside a <BOLD> section.
charAt(index) Returns the character in the string at position index.
fixed() Causes its string to behave as though it is inside a <FIXED> section.
fontColor(color) Causes its string to behave as though it is inside a <FONT> section with the COLOR attibute set to color, where color is an RGB triplet.
fontSize(size) Causes its string to behave as though it is inside a <FONTSIZE> section, where size is a value between 1 and 7.
indexOf(searchstring, startindex) Searches its string for an occurrence of searchstring starting at startindex or, if startindex is not provided, at zero. Returns the index of the first occurrence or -1 if the searchstring is not found.
italics() Causes its string to behave as though it is inside an <I> section.
lastindexOf(searchstring, startindex) Searches its string for an occurrence of searchstring starting at startindex or, if startindex is not provided, at zero. Works from the back of the string to the front. Returns the index of the last occurrence or -1 if the searchstring is not found.
link(href) Causes its string to behave as though it is inside an <A> section with the HREF attribute set to href.
small() Causes its string to behave as though it is inside a <SMALL> section.
strike() Causes its' string to behave as though it is inside a <STRIKE> section.
sub() Causes its string to behave as though it is inside a <SUB> section.
substring(startindex, endindex) Returns a string that is a substring of this string object between startindex and endindex. If startindex is greater than endindex, the string is reversed.
sup() Causes its string to behave as though it is inside a <SUP> section.
toLowerCase() Returns an all-lowercase version of its string.
toUpperCase() Returns an all-uppercase version of its string.

Listing 7.20 shows how the string manipulation functions work.

Listing 7.20 string01.asp.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var Str1 = "Hello World"
window.document.writeln("<PRE>")
window.document.writeln("Str1.lenght = " + Str1.length)
window.document.writeln("Str1.toUpperCase = " + Str1.toUpperCase())
window.document.writeln("Str1.toLowerCase = " + Str1.toLowerCase())
window.document.writeln("Str1.substring(0,5) = " + Str1.substring(0,5))
window.document.writeln("</PRE>")
-->
</SCRIPT>


The Math Object

The 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).

Property Definition
E Euler's Constant, about 2.72. Base for natural logarithms.
LN10 The natural logarithm of 10, about 2.30
PI The value of pi, about 3.14
SQRT_2 The square root of 0.5, about 7.71
SQRT2 The square root of 2, about 1.41


Table 7.8. Math object (methods).

Methods Definition
abs(number) The absolute value of number
acos(number) The arc cosine of number in radians
asin(number) The arc sine of number in radians
atan(number) The arc tangent of number in radians
ceil(number) The next integer greater than number
cos(number) The cosine where number is radians
exp(number) The value of E raised to the number power
floor(number) The next integer less than number
log(number) The natural logarithm of number
max(num1, num2) The greater of num1 and num2
min(num1, num2) The lesser of num1 and num2
pow(num1, num2) Num1 raised to the num2 power
random() A random number between zero and one
round() Rounds to closest integer to number
sin(number) The sine where number is radians
sqrt(number) The square root of number
tan(number) The tangent where number is radians

Listing 7.21 gives you a general idea about how to use these functions.

Listing 7.21. math.asp.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var angle = Math.PI/6
with (Math)
{
window.document.writeln("<PRE>")
window.document.writeln("sin(angle) = " + sin(angle))
window.document.writeln("cos(angle) = " + cos(angle))
window.document.writeln("round(angle) = " + round(angle))
window.document.writeln("exp(angle) = " + exp(angle))
window.document.writeln("</PRE>")
}
-->
</SCRIPT>

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:

sin(angle) = 0.5
cos(angle) = 0.866025403784439
round(angle) = 1
exp(angle) = 1.68809179496447


The Date Object

The JavaScript Date object has zero properties and twenty methods. Define a new Date variable with the syntax:

Mydate = new Date(dateinfo)

where dateinfo is an optional indicator of the date format that can have one of three formats:

  • month day, year hours:minutes:seconds

  • year, month, day

  • year, month, day, hours, minutes, seconds

The methods that go with the Date object appear in Table 7.9.

Table 7.9. The Date object.

Methods Definition
getDate() Returns an integer representing the day of the month from its Date
getDay() Returns an integer representing the day of the week from its Date object where 0 is Sunday
getHours() Returns an integer representing the hour from its Date from 0 to 23(military or European time)
getMinutes() Returns an integer representing the minute from its Date object from 0 to 59
getMonth() Returns an integer representing the minute from its Date object from 0 to 11, where 0 is January
getSeconds() Returns an integer representing the second from its Date object from 0 to 59
getTime() Returns an integer representing the time from its Date object since midnight, 1 January 1970, in milliseconds
getTimezoneOffset() Returns an integer representing the difference in the time zone from its Date object to GMT in minutes
getYear() Returns an integer representing the year from its Date object from 0 to 99, assuming 1900 as the base year.
parse(datestring) Like getstring, except datestring is used to determine the number of milliseconds since midnight, 1 January, 1970. datestring has the format:
  • day, DD Mon YYY HH:MM:SS TZN (Sun, 15 May 1955 07:52:00 GMT)
  • Mon DD, YYYY (May 15, 1955)
setDate(timevalue) Sets the day of the month in its Date object where timevalue is between 1 and 31
setHours(timevalue) Sets the hour in its Date object where timevalue is between 0 and 23
setMinutes(timevalue) Sets the minute in its Date object where timevalue is between 0 and 59
setMonth(timevalue) Sets the month in its Date object where timevalue is between 0 and 11, and where 0 is Jan.
setSeconds(timevalue) Sets the seconds in its Date object where timevalue is between 0 and 59
setTime(timesince) Sets the value of its Date object where timesince is milliseconds from midnight, 1 January, 1970
setYear(timevalue) Sets the year in its Date object where timevalue is greater than 1900
toGMTString() Returns a string based on the current Date object in the form Day, DD Mon YYYY HH:MM:SS GMT
toLocalString() Returns a string based on the current Date object in the format specified when the Date object was created.
UTC(year, month, date, (hours, minutes, seconds) Like getstring, except UTC is used to determine the number of milliseconds since midnight, 1 January, 1970 GMT and the entered date.

Listing 7.22 shows how these functions can be used.

Listing 7.22 date.asp.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var mydate = new Date()
window.document.writeln("<PRE>")
window.document.writeln("mydate = " + mydate)
window.document.writeln("mydate.getHours() = " + mydate.getHours())
window.document.writeln("mydate.time() = " + mydate.getTime())
window.document.writeln("</PRE>")
-->
</SCRIPT>


Program Flow

JavaScript 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.

if

You have already used this function close to a hundred times this week, but not many in JavaScript. The general syntax is:

if(condition)
{
//some statements that execute if condition is true
}
else
{
//some statements that execute if condition is false

Listing 7.23 illustrates the if function.

Listing 7.23. flow01.asp.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
choice = 3
window.document.open()
window.document.writeln("<PRE>")
if (choice == 1)
{
window.document.write("Choice is 1")
}
else
{
if (choice == 2)
{
window.document.write("Choice is 2")
}
else
{
window.document.write("Choice is 3")
}
}
window.document.writeln("</PRE>")
window.document.close()
-->
</SCRIPT>

The result of this page is as follows:


Choice is 3

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.

for

This function allows you to perform selected program statements a given number of times. The syntax is:

for ([initial-expression;] [condition;] [increment-expression])
{
statements
}

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.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var string1 = "12345678"
var limit = string1.length
// window.document.open()
window.document.writeln("<PRE>")
for(var i = 0;i < limit; i++)
{
window.document.writeln(string1.charAt(i))
}
for( i = (limit - 1); i >= 0 ;i--)
{
window.document.writeln(string1.charAt(i))
}
window.document.writeln("</PRE>")
// window.document.close()
-->
</SCRIPT>

Listing 7.24 produces the following:

1*2*3*4*5*6*7*8*
8*7*6*5*4*3*2*1*

Notice how the string method charAt90 was used to read the characters.

while

The 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:

while (condition)
{
statements
}

Listing 7.25 provides an example of the while statement.

Listing 7.25. flow03.asp.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
var target = "Now is The Time"
var Teststring = "T"
var CurrentString = ''
var count = 0
window.document.open()
window.document.writeln("<PRE>")
while ((target.charAt(count) != 'T') && (count <= target.length))
{
window.document.write(target.charAt(count) + "*")
count++
}
window.document.writeln("</PRE>")
window.document.close()
-->
</SCRIPT>


for...in

The for...in statement is called an iterater. An iterater cycles through all the things in a collection. The for—in statement in JavaScript cycles through all the members of an object. The syntax is:

for (variable in object)
{
// program statements
}

Aim the result of Listing 7.26 at the object you created in object04.asp (Listing 7.17).

Listing 7.26. flow04.asp.

<SCRIPT LANGUAGE="JavaScript">
<!--
function MyObject(type, height, width, x, y)
{
this.type = type
this.height = height
this.width = width
this.pos = new Position(x,y)
this.printme = Printout
}
function Position(x,y)
{
this.x = x
this.y = y
}
function Printout()
{
window.document.writeln("<PRE>")
window.document.writeln('type = ' + this.type)
window.document.writeln('height = ' + this.height)
window.document.writeln('width = ' + this.width)
window.document.writeln('x value= ' + this.pos.x)
window.document.writeln('y value = ' + this.pos.y)
window.document.writeln("</PRE>")
}
-->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
window.document.open()
Shape1 = new MyObject("Circle", 10, 25, 24, 167)
Shape1.printme()
Shape2 = new MyObject('Shape2',1,1,0,0)
Shape2.printme()
for (var i in Shape1)
{
Shape2[i] = Shape1[i]
}
Shape2.printme()
window.document.close()
-->
</SCRIPT>

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 Elements

JavaScript 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


alert(message)

where message is optional and evaluates to a printable value.

The prompt box, with the following syntax, is a little more complex:

prompt(message, [Default])

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:

confirm(message)

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.

<SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
<!--
alert("Get Ready")
var answer = prompt("Enter a Number","63")
while(confirm("Pick Another Number?"))
{
answer = prompt("Enter another Number","63")
}
alert("Last item picked was" + answer)
-->
</SCRIPT>

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.


Summary

It 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

  • Q I wrote the following code; it seems to follow all the rules, but I get an error saying that Rose is undefined. What is wrong?
    • 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() 
      -->.
  • A On the surface, the code looks okay. You either declared or set up a new variable by assigning a value. What happened is that you used Rose by assignment before you created it. Even if you create it with the var statement, you still get an error. If you switch it with the ROse = Rose + ROSE statement, you will have the same problem. Declare the variables, then rewrite the code like this:

    <SCRIPT LANGUAGE="JavaScript" FOR="window" EVENT="onLoad()">
    <!--
    // Your Code Here
    var ROSE
    Rose = 1
    var ROSE = 0
    var ROse = 0
    ROSE = ROse + 4
    Rose + ROSE
    document.open()
    document.writeln("<PRE>")
    document.writeln(Rose)
    document.writeln(ROSE)
    document.writeln(ROse)
    document.writeln("</PRE>")
    document.close()
    -->
    </SCRIPT>
  • Q Question Why are there differences between JavaScript and VBScript? Which one should I choose?

  • A JavaScript, as you saw today, is object oriented, whereas VBScript it a procedural language. If you have lots of C, C++, or Java experience, I suggest you use JavaScipt because the syntax and the object-oriented mind-set are similar. VBScript, on the other hand, has a shorter learning curve. Non-programmers can become proficient in less time. If you have little programming experience and need something fast, use VBScript.

  • Q Question How do you think JavaScript will evolve from here?

  • A I predict that JavaScript will mature over the next year rather than evolve. I think that the object-oriented model of JavaScript will make it the programmers choice for Web sites, especially large, complicated Web sites. You can do a lot more than just connect the dots with JavaScript.

  • Q Are arrays 0 (first element is 0) or 1 (first element is 1) based?

  • A Since you build your own array objects, you are free to make them 0 or 1 based.


Workshop

Add a copy method to Object04.asp that allows the user to copy the contents of another like object(hint: see flow04).

Quiz

  1. Would you be more likely to use JavaScript on a math-intensive application or a string-intensive application? Why?

  2. Which are illegal variables in JavaScript: MY.NAME, MyName, or 4Things?

What control structure can I use to get information out of my home-made object?



Previous Next