Functions

Programs often need to perform a particular set of actions under many different circumstances. A function is a named block of program code that can be run at any time simply by calling the function's name. As you learned in Chapter 6, you can define a function in JScript by using the function keyword followed by the name of the function and a set of parentheses. The block of script enclosed in curly braces ( { and } ) that follows the parentheses defines the actions that the function will perform. For instance, the following code creates a function named greetUser that contains script to display in an Alert dialog box:

 function greetUser(){alert("Hi there. This is a dialog box.")} 

The greetUser function can now be called at any time by using its name (including the parentheses). For instance, the following BUTTON tag has an embedded event handler that calls the greetUser function whenever the button is clicked:

 <BUTTON onclick="greetUser()">Hello</BUTTON> 

NOTE
One somewhat unusual feature of JScript is that functions can be treated like variables or data. Because of this, you can use functions in ways that are not possible in many other programming languages. For example, one function can be passed to another function as an argument, or different indexes of an array can be assigned different functions.

Arguments

Arguments, which are placed in the parentheses following the function name, provide a mechanism by which information is passed to a function. You can pass multiple arguments to a single function by separating them with commas. Code Listing 9-1 demonstrates the use of a function with two arguments. In Figure 9-1, you can see what the browser displays after one of the buttons specified in the code has been pressed.

Code Listing 9-1.

 <HTML> <HEAD> <TITLE>Listing 9-1</TITLE> <SCRIPT LANGUAGE="JavaScript"> function changeIt(target,newText){   oldText=target.value   target.value=newText   alert("The button that read `"+oldText+"` now reads `"+newText+"`.") } </SCRIPT> </HEAD> <BODY> <FORM>   <INPUT TYPE="button" VALUE="Btn1" onclick="changeIt(this,'One')"><BR>   <INPUT TYPE="button" VALUE="Btn2" onclick="changeIt(this,'Two')"><BR>   <INPUT TYPE="button" VALUE="Btn3" onclick="changeIt(this,'Three')"><BR> </FORM> </BODY> </HTML> 

click to view at full size.

Figure 9-1. An Alert dialog box appears after a button is clicked.

In Code Listing 9-1, we initially set the text of each of the buttons with the VALUE attribute. Each button has an onclick event handler that calls the changeIt function when the element is clicked. Two arguments are passed to the changeIt function: the first is the keyword this (which returns the current object), and the second is the new text that we want in the button.

The passed values are assigned to the target and newText variables in the function, in that order. The function first saves the old value of the button in a variable named oldText that is used later in an alert. The target and newText variables are used to change the text of the clicked button and to alert the user to what has occurred.

Also notice that when we passed arguments when calling the changeIt function, the second argument appeared in quotation marks, while the first argument did not. Enclosing an argument in quotation marks means that the argument should be treated as a string. You do not use quotation marks when passing a non-string type, such as a number, an object, or a variable (even a variable that contains a string). The first argument passed in Code Listing 9-1 is a reference to the object that was clicked. Passing a reference to the button itself allows access to the button's properties directly through the function's target variable. If we had enclosed the word this in quotation marks, we would have simply passed to the function a string containing the letters t, h, i, and s rather than the object itself. A real-world equivalent might be the difference between giving someone a car and telling the person the name of the car. The second argument we passed is a string containing the text we want for the button.

Returns

You just saw how to pass data to a function by using arguments. To get information back from a function, you can use a return. The return keyword causes a function to evaluate to a result—that is, to "return" a value when it is run. You can use this mechanism to assign the return value of a function to a variable or use the returned value in some other way. Code Listing 9-2 demonstrates the use of a return value; in Figure 9-2, you can see what this code does.

Code Listing 9-2.

 <HTML> <HEAD> <TITLE>Listing 9-2</TITLE> <SCRIPT LANGUAGE="JavaScript"> function rndNum(maxNum){   num=Math.random()   num=num*maxNum   num=Math.ceil(num)   return num } function tellUser(specifiedNum){   alert(rndNum(specifiedNum)) } </SCRIPT> </HEAD> <BODY> Type a number in the area below, and then click Calculate.<BR> The page will generate a random number between 1 and the  number you entered.<BR> <FORM> <TEXTAREA NAME="TextNum">10</TEXTAREA> <BR> <INPUT TYPE="button" VALUE="Calculate"         onclick="tellUser(TextNum.value)"> </FORM> </BODY> </HTML> 

click to view at full size.

Figure 9-2. Retrieving a value from a function.

Code Listing 9-2 illustrates how an argument is passed to a function, how one function can call another, and how the return keyword is used. Clicking the Calculate button calls the tellUser function, passing the value of the TEXTAREA named TextNum as an argument. The tellUser function then produces an Alert dialog box. This dialog box displays the value returned by the rndNum function, which first generates a random number between 0 and 1, multiplies that number by the argument that was passed to it, and then rounds the resulting number upward. This final value is returned to the tellUser function and is then displayed on screen in the Alert dialog box.

NOTE
Code Listing 9-2 should work in Netscape Navigator or Microsoft Internet Explorer versions 4 or later. To do the same thing in the version 3 browsers, you cannot use the simple syntax TextNum.value to refer to the number in the text area. Instead, you should use the older syntax document.forms[0].elements[0].value to accomplish the same goal. Another difference between browsers is that Internet Explorer does not require the FORM tags around the INPUT and also allows a BUTTON tag to be used instead.

If you were designing a similar Web page that was destined for the real world, you would want to do some error checking to ensure that the data being passed to the function was a number. In Code Listing 9-2, if you use a letter or a word instead of a number, the page displays NaN, which means that the value passed was not a number. In the next section, we will explore methods of testing data that can be used for error checking.



Dynamic HTML in Action
Dynamic HTML in Action
ISBN: 0735605637
EAN: 2147483647
Year: 1999
Pages: 128

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net