|
|||
|
EarthWeb sites: |
Chapter 23JavaScript 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.
The JavaScript Object ModelAn 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" 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> And then use the pointer to that object to access each of the individual variables: <SCRIPT> MethodsMethods, 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 ObjectsYou 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"> 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) { 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"; 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 MethodsIn 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 Listing 23.1 method.html Creating Objects and Methods <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.
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 ConditionsConditions 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.)
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 OperatorsThe 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)) 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 elseSo 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) { 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) {
The else and related statements
are not required if you simply want the if
state- if (errorLevel == 1) { 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 StatementsThe 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) { 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) { 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) { As long as the condition evaluates to true, the loop will continue. An example is the following: x = 0; 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) {
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 BREAK and CONTINUETwo 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) { 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) { 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 DecrementsSo 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) { 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 Examples: Looping and ConditionsLet'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> 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.
Built-in ObjectsIn 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 ObjectWe'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.
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>"); 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 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 DecimalsLet'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> 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 ObjectThe 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;
Table 23.3 shows you the various properties for PI.
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.
Example: Rounding for DollarsWith 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> 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 JavaScriptAlthough 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. SummaryOnce 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
Review Exercises
|
Use of this site is subject certain Terms & Conditions. Copyright (c) 1996-1999 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Please read our privacy policy for details. |