Chapter 23

JavaScript Objects and Functions


CONTENTS


In the last chapter, you learned enough JavaScript to accomplish some pretty impressive things, like error checking on forms, creating alert messages, and performing simple functions like math. In this chapter, you get a little deeper into how JavaScript and Netscape Navigator store values for scripting. Then you learn how you can use this knowledge to do even more sophisticated things with JavaScript.

Note
This chapter assumes you have some experience with computer programming languages. JavaScript is a fairly simple scripting language for the "initiated," but this chapter may be less than useful if you've had no exposure to programming or script authoring concepts.

The JavaScript Object Model

An object, for the purposes of this discussion, is basically a collection of properties. Often, these properties are variables, but they can also be functions or JavaScript methods. Properties within objects are accessed using the following notation:

objectName.propertyName

For instance, if you created an object called myComputer, you might have properties called diskspace, monitor, and cdspeed. You could assign values to those properties like this:

myComputer.diskspace = "2.4 GB"
myComputer.monitor = "17-inch VGA"
myComputer.cdspeed = "6x"

What we've basically done is assign values to variables that happen to all be associated with one another since they're part of my computer (and myComputer). So you could pass this object to a function using the following function call:

<SCRIPT>
printSpec (myComputer);
</SCRIPT>

And then use the pointer to that object to access each of the individual variables:

<SCRIPT>
function printSpec (computer) {
   document.write ("Disk space = " + computer.diskspace + "<BR>">);
   document.write ("Monitor = " + computer.monitor + "<BR>");
   document.write ("CD Speed = " + computer.cdspeed + "<BR>");
   return;
   }
</SCRIPT>

Methods

Methods, then, are basically functions associated with objects. For instance, one of the methods we've used quite a bit is document.write, which is really just a function provided by JavaScript that allows you to write HTML code to the current document.

Notice, then that write is the function, and document is the associated object. Netscape Navigator and other JavaScript browsers define certain basic objects, like document, that are designed to make it easier for you to deal with the document or window in question. You'll learn about some of those standard objects later in this chapter.

You can even create your own methods by simply assigning a function name to an object variable, following this format:

object.methodname = function_name

Creating New Objects

You may remember that you used the keyword this for an object reference in the last chapter. JavaScript offers you the special keyword this, which acts as a placeholder. It's used to represent the current object involved in a function call. An example is the following:

<FORM NAME="MyForm">
<INPUT TYPE="Text" NAME="first" onClick="check(this)">
</FORM>

This sends a pointer to the current object to the function check. In this case, the actual object is document.myform.first, but the keyword this can be used here since it's clear what the current object is.

That's part of how you create your own objects. It's done in two steps. First, you need to define a function that outlines the basic object you'd like to create. This is your own personal object definition for this new type of object.

For instance, if you wanted to create a data object that could be used to describe a person, you might use the following function:

function person(name, height, weight, age) {
   this.name = name;
   this.height = height;
   this.weight = weight;
   this.age = age;
   }

Notice the use of this. In the case of this example here, this refers to the object that's being created by another keyword, new. Using new is the second step in creating your new object. The following is an example:

debbie = new person("Debbie", 5.5, 130, 27) ;

The keyword new creates a new object. It also tells the object-creating function person that the name of this new object will be debbie. So when the function is called, debbie will replace this and the assignment will work like this:

debbie.name = "Debbie";
debbie.height = 5.5;
debbie.weight = 130;
debbie.age = 27;

Of course, you won't see any of this happen. But it's now possible for you to access this data just like a regular object, as in the following:

document.write("Debbie's age is: ",debbie.age);

Example: Creating New Objects and Methods

In this example, you'll create a script that not only creates a new object but creates a method within that object. The object will be designed to hold data concerning a user's purchase. The method will be designed to generate a total of what is owed. You can use HTML form tags to allow the user to enter the information.

You start out by defining all of your functions in the head of the document
and then creating the form in the body. Create a new HTML document and enter Listing 23.1.


Listing 23.1  method.html  Creating Objects and Methods
<HTML>
<HEAD>
<TITLE>Customer Purchases</TITLE>
<SCRIPT>
<!--
function customer (val1, val2, val3) {
   this.item1 = val1;
   this.item2 = val2;
   this.item3 = val3;
   this.getsum = getsum;
   }

function getsum (form) {
   var total = 0
   total = this.item1 + this.item2 + this.item3;
   form.Sum.value = total;
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3> The amount of each puchase is: </H3>
<PRE>
Purchase 1:   $5
Purchase 2:   $10
Purchase 3:   $12
</PRE>
<SCRIPT>
<!--
cust1 = new customer (5, 10, 12);
// -->
</SCRIPT>
<FORM NAME="form1">
<INPUT TYPE="BUTTON" NAME="Total" VALUE="Get Total" onClick="cust1.getsum
(this.form)">
<INPUT TYPE="TEXT" NAME="Sum" SIZE="12">
</FORM>
</BODY>
</HTML>

Notice first that the function that defines the object, called customer, uses the keyword this to reference its individual properties. When the new object is created, it's called cust1 and the new keyword passes that name to the object creator. So, in the onClick statement, you can then call the object's properties using cust1, as in cust1.item1 or cust1.getsum.

In fact, cust1.getsum is a special case-it's the method you're creating in this example. All you have to do is assign the function getsum as a property of your object and then you can call it using object notation, as in cust1.getsum (this.form). Notice that the function getsum() is designed to accept a pointer to form data. See figure 23.1 for an example of how this will look in a browser.

Figure 23.1 : Your object and method example.

JavaScript Statements

If you have any experience with programming languages, you'll be familiar with JavaScript's small set of statements. JavaScript includes the conditional statement if...else and the loop statements for, while, break, and continue. You'll also get to know some of the associated JavaScript operators.

Tip
Remember that, in most cases, you'll use these statements in functions. These are the commands in JavaScript you'll use to actually process data.

The key to many of these statements is called the condition, which is simply a bit of JavaScript code that needs to be evaluated before your script decides what to do next. So before you look at JavaScript statements, let's look at the conditions and operators that JavaScript recognizes.

Comparison Operators and Conditions

Conditions are generally enclosed in parentheses, and they are always a small snippet of code that is designed to evaluate as true or false. For instance, the following is a conditional statement:

(x == 1)

If x does equal 1, then this condition is valid.

And this is why it's important to recognize and use the correct operators for conditions. For instance, an assignment always evaluates to true, so that the following condition:

(errorLevel = 1)

is always true since it's an assignment. Although it may seem to make sense to use an equal sign in this instance, you actually need to use the comparison operator == for this condition. (See Table 23.1 for a listing of the comparison operators.)

Table 23.1  Comparison Operators in JavaScript

OperatorMeaning
Example
Is True When…
== equals
x == y
x equals y
!= not equal
x != y
x is not equal to y
> greater than
x > y
x is greater than y
< less than
x < y
x is less than y
>= greater than or equal to
x >= y
x is greater than or equal to y
<= less than or equal to
x <= y
x is less than or equal to y

So you have a number of different ways to create conditions by using comparisons. Realize, too, that conditions are not necessarily limited to numerical expressions. For instance, look at the following:

(carName != "Ford")

This will return the value false if the variable carName has the value of the string Ford.

Boolean Operators

The other operators common to conditional statements are the boolean operators. In English, these operators are AND, OR, and NOT. In JavaScript, AND is &&, OR is ||, and NOT is !. An example of a condition is the following:

((x == 5) && (y == 6))

This condition evaluates to true only if each individual comparison is true. If either comparison is false-or both comparisons are false-the entire conditional statement is false.

On the other hand, the following conditional statement uses the OR operator:

((x == 5) || (y == 6))

In this case, if either of the conditions is true, then the entire statement is true. The statement is only false if both of the conditions are false.

Finally, the NOT operator changes the result of an expression, so that assuming
x == 5, you can create the following conditional:

(!(x == 5))

NOT simply reverses the result of the conditional statement. In this example, the entire condition is false since (x == 5) is true, and the NOT operator reverses that.

if…else

So how do you put these conditional statements and operators to use? JavaScript offers the if...else conditional statement as a way to create either/or situations in your script. The basic construct is as follows:

if (condition) {
  script statements }
else {
  other statements }

The condition can be any JavaScript that evaluates to either true or false. The statements can be any valid JavaScript statements. For example:

if (x == 1) {
  document.write("X equals 1!");/
  return;
  }
  else {
  x = x + 1;
  }

The else and related statements are not required if you simply want the if state-
ments to be skipped and the rest of the function executed. An example might be:

if (errorLevel == 1) {
   return (false);
   }

In this case, if the condition is false (e.g., errorLevel does not equal 1), then the rest of the function executes. If it is true, then the function ends.

Loop Statements

The next two statement types are used to create loops-script elements that repeat until a condition is met. These loop statements are FOR and WHILE.

A FOR loop follows the basic construct:

for (initial_assignment; condition; increment) {
     JavaScript statements
     }

You'll generally start a FOR loop by initializing your "counter" variable. Then you'll evaluate the counter to see if it's reached a certain level. If it hasn't, then the loop will perform the enclosed statements and increment your counter. If the counter has reached your predetermined value, then the FOR loop ends. For example:

for (x=0; x<10; x=x+1) {
   y = 2 * x;
   document.write ("Two times ",x," equals ",y,"<BR>");
   }

You start by initializing a counter variable (x=1) and then evaluating the counter in a conditional statement (x<10). If the condition is true, then the loop will perform the enclosed scripting. Then it will increment the counter-in this case, add 1 to it. When the counter reaches 10 in your example, the loop will end.

The WHILE loop is similar to the FOR loop, except that it offers a little more freedom. WHILE is used for a great variety of conditions. The basic construct is as follows:

while (condition) {
  vaScript statements
  

As long as the condition evaluates to true, the loop will continue. An example is the following:

x = 0;
while (x <= 5) {
   x = x +1;
   document.write (X now equals ",x,"<BR>")
   }

As long as the condition remains true, the WHILE statement will continue to evaluate. In fact, the risk with WHILE statements is that they can be infinite if the expression never evaluates to false. A common mistake is the following:

while (x=5) {
  x = x +1;
  document.write (X now equals ",x,"<BR>")
  }

The condition is actually an assignment, so it will always evaluate to true. In this example, the loop would continue indefinitely, and the output would always be
X now equals 6.

BREAK and CONTINUE

Two other keywords, BREAK and CONTINUE, can be used in FOR or WHILE loops to change the way the loop operates when certain conditions occur. Notice that both of these are generally used with an if statement.

An example of BREAK is:

for (x=0; x < 10; x=x+1) {
    z = 35;
    y = z / x;
    if (y == 7)
       break;
    }

BREAK will terminate the loop when encountered. In this example then, the loop is terminated when x is equal to 5 since 35 divided by 5 is 7. When the condition (y == 7) evaluates to true, the loop stops and you move on to the next script element.

CONTINUE is basically used to skip a particular increment. For instance:

while (x < 10) {
    x = x +1;
    if (x == 5)
       continue;
    y = y + x;
    }

In this case, when the condition (x == 5) evaluates to true, the CONTINUE statement will cause the loop to move directly back to the WHILE statement, thus skipping over the last line (y = y + x). When the condition is false, the last line will execute normally.

Increments and Decrements

So far, you've seen me using statements like x = x + 1 in many of these examples to increment the values in your loop statements. JavaScript allows you to do this in other ways, using unary operators. A unary operator is an operator that requires only one operand, as in the unary increment operator:

x++

In fact, you can increment with either x++ or ++x. The difference is when the increment occurs, for instance, if x equals 2:

y = x++

y will be assigned the value 2, then x will be incremented to 3. In the following example, though:

y = ++x

x will first be incremented to 3, then y will be assigned 3. This is especially significant in loop statements. Where x++ would work in past examples, it should be noted that the following will actually increment x before performing the rest of the script elements:

for (x=0; x < 5; ++x) {
    x;
   }

In this case, the first assignment to y would actually have a value of 1, instead of 0.

Decrementing works the same way, with both x-- and --x as possibilities. Both work similarly to x = x - 1, except that --x will decrease before being assigned or used in a loop statement.

It is also possible to assign variables at the same time you increment or decrement. Generally, you would do this with an expression like the following:

x = x + y

However, this is also possible with the unary operators += and -=. For instance, the previous example could be written as:

x += y

Similarly, the following two expressions yield the same result:

y = y - 2
y -= 2

Examples: Looping and Conditions

Let's create an example that incorporates the statements and operators you've seen thus far. In this example, the user enters a number on the page. If the number is within a certain range, it is accepted and you move on. If not, then the user is given an alert and asked to enter a new number.

The number will then increment or decrement until it reaches ten. As it does so, it will print results to a text area on the screen. The user will see the progress as the script counts toward ten.

Create a new HTML page and enter Listing 23.2.


Listing 23.2  condition.html  Increment or Decrement with Results
<HTML>
<HEAD>
<TITLE>Looping and Conditions Script</TITLE>
<SCRIPT>
<!--
function countTen (user_num, form) {
     if ((user_num < 0) || (user_num > 20)) {
      alert("Please enter a number between 0 and 20.");
      return;
   }
   while (user_num != 10) {
      if (user_num < 10) {
          addition = "Adding 1...value is now " + (++user_num) + "\r\n";
          form.results.value += addition;
      }
      else {
          subtraction = "Subtracting 1...value is now " + (--user_num) +
       "\r";
          form.results.value += subtraction;
      }
   }
   return;
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3> Please enter a number between 0 and 20 </H3>
<FORM NAME="form1">
Your Number: <INPUT TYPE="TEXT" NAME="number" SIZE="3">
<INPUT TYPE="Button" VALUE="Submit Number" onClick="countTen (this.form.number.value, this.form)">
<HR>
<H4> The result: </H4>
<TEXTAREA NAME="results" COLS="60" ROWS="10"></TEXTAREA><BR>
<INPUT TYPE="RESET" VALUE="Clear Form">
</FORM>
</BODY>
</HTML>

This may take some wading through, but it works-and it should eventually make sense.

Starting in the body of the document, the form requests a number from the user. When the user enters that number and clicks the Submit button, that number's value and a pointer to the form object are sent to the function declaration.

The first if statement determines whether or not the number is between 0 and 20. If it isn't, an alert is shown and the user is asked to enter another number. If it is between 0 and 20, you move on to the WHILE statement.

The WHILE statement will only loop until the value of your number reaches ten. If the value is not currently ten, then the if...then statement will determine whether or not you need to increment or decrement the number to move it toward ten. It then prints the statement, incrementing or decrementing the number while, at the same time, adding the text string to the form's results property.

When the function returns, there's a new value for the TEXTAREA named results. So those strings are printed, and you can see what the script did to move the original number toward ten (see fig. 23.2).

Figure 23.2 : The result of looping and conditions example.

Note
This example introduces two miscellaneous scripting ideas. First, notice that you can use an addition sign (+) to piece together a string. "You and " + "me" results in the string "You and me". Also notice the carriage return character \r\n. This carriage return varies from platform to platform. In Windows, use \r\n; UNIX and Macs use \n. (When you have to choose one, the Windows style works best.) In Chapter 30, "HTML Examples," you'll look at slightly more complicated examples that format correctly on all platforms.

Built-in Objects

In authoring scripts, there are a number of things you're likely to do over and over again. Instead of forcing you to write your own functions and create your own objects to achieve this, JavaScript includes some of these often used calls in the language itself. The built-in objects tend to store useful values or offer convenient methods. The functions usually perform some fairly intensive calculating that you'll often need to use.

The String Object

We'll talk about two major built-in objects available to you in JavaScript. The first is the string object, which helps you manipulate your strings. The math object holds certain constant values for you to use in your script and methods that make it a little easier to perform some mathematical functions.

The first object, the string object, is interesting if only for the fact that you don't actually have to use the notation string.property to use it. In fact, any string you create is a string object. You can create a string as simply as this:

mystring = "Here's a string"

The string variable mystring can now be treated as a string object. For instance, to get a value for the length of a string object, you can use the following assignment:

stringlen = mystring.length

When you create a string (and JavaScript makes it a string object), the value of its length is stored in the property length. It also associates certain methods with the object, like toUpperCase. You could change a string to all uppercase letters with the following line:

mystring = mystring.toUpperCase

If the string had the value Here is a string, this assignment changes it to HERE IS A STRING. Table 23.2 shows some of the other methods available with string objects.

Table 23.2  Methods for JavaScript String Objects

MethodWorks Example
anchor between <A NAME=> tags mystring.anchor (section_name)
big between <BIG> tags mystring.big()
blink between <BLINK> tags mystring.blink()
bold between <B> tags mystring.bold()
charAt by choosing single letter at index mystring.charAt(2)
fixed between <TT> tags mystring.fixed()
fontcolor between <FONT COLOR=> tags mystring.fontcolor("red")
fontsize between <FONT SIZE=> tags mystring.fontsize(2)
indexOf by finding index of certain lettermystring.indexOf("w")
italics between <I> tags mystring.italics()
lastIndexOf by finding occurrence before indexOf mystring.lastIndexOf ("w")
link between <A HREF=> tags mystring.link ("http://www.com")
small between <SMALL> tags mystring.small()
strike between <STRIKE> tags mystring.strike()
sub between <SUB> tags mystring.sub()
substring by choosing part of a stringmystring.substring (0,7)
sup between <SUP> tags mystring.sup()
toLowerCase by changing string to lowercasemystring.toLowerCase()
toUpperCase by chaging string to uppercasemystring.toUpperCase()

Most of these methods should be fairly self-explanatory-they allow you to use the method to create and print text as if it were between HTML tags. For instance, the following two script lines have the same results:

document.write("<BIG>" + mystring + "</BIG>");
document.write(mystring.big);

Some of the other tags take some explaining-especially those that deal with indexes. Every string is "indexed" from left to right, starting with the value 0. So in the following string, the characters are indexed according to the numbers that appear under them:

Howdy, boy
0123456789

In this case, using the method howdystring.charAt(4) would return the value y. You could also use the method howdystring.indexOf("y"), which would return the value 4.

Example: Talking Decimals

Let's see how this string stuff can be useful. What you'll do is a little bit of math involving decimal numbers, known to programmers as "floats" because they include a floating decimal point. The problem is, when you use dollars and cents decimals, you can get in trouble with JavaScript because it tends to return as many decimal places as possible. This is actually a bug (of sorts) in certain Netscape versions, and it may be changed some time in the future. In the meantime, you'll need to use these string methods to display things correctly.

Create a new HTML page and enter Listing 23.3.


Listing 23.3  strings.html  Numbers as Strings in JavaScript
<HTML>
<HEAD>
<TITLE> Doin' Decimals </TITLE>
<SCRIPT>
<!--
function sumValues (val1, val2, val3, form) {
   sum = val1 + val2 + val3;
   form.total.value = sum;
   return;
   }
function findPoint (form) {
   tot = form.total.value;
   var point_idx = tot.indexOf(".");
   form.results.value = tot.substring (0,point_idx+3);
   return;
   }
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3> The Sum of Your Purchases is:</H3>
<SCRIPT>
<!--
var pur1 = 4.95;
var pur2 = 10.95;
var pur3 = 12.50;
// -->
</SCRIPT>
<FORM>
<INPUT TYPE="Button" VALUE="Click to Compute" onCLICK="sumValues
(pur1, pur2, pur3, this.form)"><BR>
<INPUT TYPE="Text" NAME="total" SIZE="10"><BR>
<INPUT TYPE="Button" VALUE="Click to Cut" onClick="findPoint (this.form)"><BR>
<INPUT TYPE="Text" NAME="results" SIZE="10"><BR>
</FORM>
</BODY>
</HTML>

There are two things to notice here. First, when you use the substring method, you need to add 3 to the index of the decimal point since the values for substring tell the method where to start (e.g., index 0) and how far to go (e.g., point_idx + 3). For example:

mystring.substring (0, 7)

This doesn't mean "get all the characters and index 0 through index 7." What it really means is "get 7 characters, starting with index 0." So since it's counting from zero, it will stop gathering characters at index 6.

Number two is simple: there's a problem with this script. It doesn't round the value. In fact, using exactly the numbers in this example, the total cheats you of nearly a full cent (see fig. 23.3). Use this exact script for a million transactions and you have the potential to loose $10,000! You'll look at rounding in the next example.

Figure 23.3 : Taking a substring of a calculated value.

The Math Object

The math object basically just holds some useful constants and methods for use in mathematical calculations. The math objects properties are mathematical constants like E, PI, and LOG10E (log, base 10, of E). You can use these by simply adding the name as math's property, as in the following example:

var pi_value = Math.PI;
area = Math.PI*(r*r);

Table 23.3 shows you the various properties for PI.

Table 23.3  Properties for the Math Object

PropertyValue
.PI Pi (approx. 3.1416)
.E e, Euler's constant (approx. 2.718)
.LN2 natural log of 2 (approx. 0.693)
.LN10 natural log of 10 (approx. 2.302)
.LOG10E base 10 log of e (approx. 0.434)
.SQRT1_2 square root of 1/2 (approx. 0.707)
.SQRT2 square root of 2 (approx. 1.414)

The math object's methods are called like any other methods. For instance, the arc sine of a variable can be found by using the following:

Math.asin(your_num);

Table 23.4 shows the methods for the math object.

Table 23.4  Methods for the Math Object

Method Result Format
.abs absolute valueMath.abs (number)
.acos arc cosine (in radians)Math.acos (number)
.asin arc sine (in radians)Math.asin (number)
.atan arc tangent (in rads)Math.atan (number)
.cos cosineMath.cos (num_radians)
.sin sineMath.sin (num_radians)
.tan tangentMath.tan (num_radians)
.ceil least integer >= numMath.ceil (number)
.floor greatest int <= numberMath.floor (number)
.exp e to power of numberMath.exp (number)
.log natural log of numberMath.log (number)
.pow base to exponent powerMath.pow (base, exponent)
.max greater of two numbersMath.max (num, num)
.min lesser of two numbersMath.min (num, num)
.round round to nearest intMath.round (number)
.sqrt square root of numberMath.sqrt (number)

Example: Rounding for Dollars

With the newly learned Math.round method, maybe you can get that last example to round dollars correctly. Create a new HTML document and enter Listing 23.4 (or make changes on the last example, using Save As to change the name).


Listing 23.4  rounded.html  Rounding Decimal Numbers in JavaScript
<HTML>
<HEAD>
<TITLE> Rounding for Dollars </TITLE>

<SCRIPT>
<!--
function sumValues (val1, val2, val3, form) {
   sum = Math.round ((val1 + val2 + val3)*100);
   form.total.value = sum * .01;
   return;
   }
function roundTotal (form) {
   var tot = form.total.value;
   var sub_total = Math.round (tot * 100);
   tot_str = "" + sub_total;
   var point_idx = tot.indexOf(".");
   result_str = "";
   y = 0;
   x = 0;
   while (x <= (point_idx+2)) {
      if (x == point_idx && y == 0) {
          result_str += ".";
          y = 1;
      }
      else {
          result_str += tot_str.charAt(x);
          x++;
       }
   }
   form.results.value = result_str;
   // form.results.value = totstr.substring (0,point_idx+3);
   return;
   }
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3> The Sum of Your Purchases is:</H3>
<SCRIPT>
<!--
var pur1 = 4.96;
var pur2 = 11.13;
var pur3 = 13.15;
// -->
</SCRIPT>
<FORM>
<INPUT TYPE="Button" VALUE="Click to Compute" onCLICK="sumValues
(pur1, pur2, pur3, this.form)"><BR>
<INPUT TYPE="Text" NAME="total" SIZE="10"><BR>
<INPUT TYPE="Button" VALUE="Click to Round" onClick="roundTotal (this.form)"><BR>
<INPUT TYPE="Text" NAME="results" SIZE="10"><BR>
</FORM>
</BODY>
</HTML>

JavaScript does weird things with math, so it's difficult to make this work exactly right. Here's my logic. Your values are passed to sumValues like before, and the same answer appears in the first textbox. (This is already weird because adding numbers shouldn't give you this odd answer. Unfortunately, this is the kind of trouble you run into with decimal math on computers.)

When you click the second button, the form is sent to roundTotal, and a subtotal is generated by multiplying the total by 100 and rounding (remember, Math.round rounds to the nearest integer). The subtotal is turned into a string, and then the while loop is implemented to find the right place for the decimal point and replaced in the rounded number. Why not just multiply by .01? Good idea, except you'd get a weird floating point number again-and you'd have to start over again!

Take special notice that the following line turns tot_str into a string variable with the value sub_total:

tot_str = "" + sub_total;

The alternative is the following:

tot_str = sub_total;

This assignment would make tot_str a numerical variable, which wouldn't work in the subsequent while loop. Figure 23.4 shows the whole thing in action.

Figure 23.4 : Finally, you've done some rounding.

Thoughts on JavaScript

Although JavaScript is a fairly easy language, it still can become very involved, and there's no way you can cover the entire thing in a few chapters. If you'd like to learn more about JavaScript, I'd suggest starting with the JavaScript Authoring Guide by Netscape Corporation at http://home.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html. If you don't have any programming experience, you might be better off picking up a book designed to teach you JavaScript from the ground up. Both Special Edition Using JavaScript and JavaScript By Example are excellent titles from Que.

JavaScript is a very powerful way to make your Web site client-side, in that it allows you to actually compute and process without the help of a Web server and special handling (like that required for CGI-BIN scripts). Even more powerful for this are full-fledged Java applets, and you may be able to find some of those that will help you do what you want on your page without much programming at all.

Summary

Once you get deeper into the JavaScript object model, you can start to see a number of easier ways to accomplish advanced scripting issues. Objects can have both properties (variables) and methods (functions) associated with them. The ability to store a number of associated values and function calls in one object makes it easier to group data and work with calculation in JavaScript.

JavaScript also includes a number of keywords and statements for creating if...else and looping statements. Using these takes some understanding of the comparison operators used in JavaScript, as well as a look at the assignment operators. These operators, which can be either binary or unary, can be used to increment, decrement, multiply, assign, and compare values or strings.

Loops can then be used to calculate something a number of times until a condition changes. You can also use the BREAK or CONTINUE statements to perform special commands when a certain condition within a loop is encountered.

JavaScript includes some of its own built-in objects, including those for math and strings. Both have properties and methods associated with them that make many common calculations easier.

Review Questions

  1. How can you assign the property at_bats (with a value of 25) to the object player2? (Assume the object already exists.)
  2. If document is an object, what is write in document.write?
  3. What is substituted for the keyword this in an object definition when a new object is created?
  4. True or false. To assign a new method to an existing object requires the new keyword.
  5. What's the difference between (x == 1) and (x = 1)? Which of these always evaluates to true?
  6. What happens if you don't include an else statement with an if condition and the if condition is false?
  7. Consider the following:

    for (x=0; x<5; ++x) {
       y = x;
    }

    The first time this loop executes, what is the value of y?
  8. In the following example, what is the final value for y?

    for (x=0; x<5; x++) {
      if (x == 4)
         continue;
      y += x;
    }
  9. How can you piece two strings together?
  10. What string method would you use to create a link to a new HTML document?

Review Exercises

  1. Create a new object function called player that creates the properties name, hits, strikeouts, atbats, and homeruns.
  2. Add a method to the above object definition that computes the batter's batting average (hits/atbats). (Baseball enthusiasts will please excuse the crudity of this model.)
  3. Write a script that defines a new player object and outputs the batter's average in a form textbox.
  4. Write a script that defines a new player object and allows the user to enter the name, hits, strikeouts, atbats, and homeruns values in a text form. Then compute the average and print the player's name and stats to a form textarea.

Note
There's something you need to know for this example. The built-in function parseInt (string_variable, 10) can be used to change a string to an integer. The parameters for this function are the name of the string variable and the base numbering system you want to use (i.e., ten for base-10 or decimal numbers). This is an important step because form values are always strings.