|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Using FunctionsThe scripts you've seen so far are simple lists of instructions. The browser begins with the first statement after the <script> tag and follows each instruction in order until it reaches the closing </script> tag (or encounters an error). Although this is a straightforward approach for short scripts, it can be confusing to read a longer script written in this fashion. To make it easier for you to organize your scripts, JavaScript supports functions, which you learned about in Hour 3, "Getting Started with JavaScript Programming." In this section, you will learn how to define and use functions. Defining a FunctionFunctions are groups of JavaScript statements that can be treated as a single unit. To use a function, you must first define it. Here is a simple example of a function definition: function Greet() {
alert("Greetings.");
}
This defines a function that displays an alert message to the user. This begins with the function keyword. The function's name is Greet. Notice the parentheses after the function's name. As you'll learn next, the space between them is not always empty. The first and last lines of the function definition include braces ({ and }). You use these to enclose all of the statements in the function. The browser uses the braces to determine where the function begins and ends. Between the braces, this particular function contains a single line. This uses the built-in alert() function, which displays an alert message. The message will contain the text "Greetings." By the Way Function names are case sensitive. If you define a function such as Greet() with a capital letter, be sure you use the identical name when you call the function. Now, about those parentheses. The current Greet() function always does the same thing: Each time you use it, it displays the same message. Although this avoids a bit of typing, it doesn't really provide much of an advantage. To make your function more flexible, you can add parameters, also known as arguments. These are variables that are received by the function each time it is called. For example, you can add a parameter called who that tells the function the name of the person to greet. Here is the modified Greet() function: function Greet(who) {
alert("Greetings, " + who);
}
Of course, to use this function, you should include it in an HTML document. Traditionally, the best place for a function definition is within the <head> section of the document. Because the statements in the <head> section are executed first, this ensures that the function is defined before it is used. Listing 6.1 shows the Greet() function embedded in the header section of an HTML document. Listing 6.1. The Greet() Function in an HTML Document
By the Way As usual, you can download the listings for this hour or view them online at this book's website. Calling the FunctionYou have now defined a function and placed it in an HTML document. However, if you load Listing 6.1 into a browser, you'll notice that it does absolutely nothing. This is because the function is definedready to be usedbut we haven't used it yet. Making use of a function is referred to as calling the function. To call a function, use the function's name as a statement in a script. You will need to include the parentheses and the values for the function's parameters. For example, here's a statement that calls the Greet function: Greet("Fred");
This tells the JavaScript interpreter to transfer control to the first statement in the Greet function. It also passes the parameter "Fred" to the function. This value will be assigned to the who variable inside the function. By the Way Functions can have more than one parameter. To define a function with multiple parameters, list a variable name for each parameter, separated by commas. To call the function, specify values for each parameter separated by commas. Listing 6.2 shows a complete HTML document that includes the function definition and a second script in the body of the page that actually calls the function. To demonstrate the usefulness of functions, we'll call it twice to greet two different people. Listing 6.2. The Complete Function Example
This listing includes a second set of <script> tags in the body of the page. The second script includes two function calls to the Greet function, each with a different name. Now that you have a script that actually does something, try loading it into a browser. You should see something like Figure 6.1, which shows the Greeting script running in Firefox. Figure 6.1. The output of the Greeting example.
By the Way Notice that the second alert message isn't displayed until you press the OK button on the first alert. This is because JavaScript processing is halted while alerts are displayed. Returning a ValueThe function you just created displays a message to the user, but functions can also return a value to the script that called them. This allows you to use functions to calculate values. As an example, you can create a function that averages four numbers. Your function should begin with the function keyword, the function's name, and the parameters it accepts. We will use the variable names a, b, c, and d for the four numbers to average. Here is the first line of the function: function Average(a,b,c,d) {
By the Way I've also included the opening brace ({) on the first line of the function. This is a common style, but you can also place the brace on the next line, or on a line by itself. Next, the function needs to calculate the average of the four parameters. You can calculate this by adding them, and then dividing by the number of parameters (in this case, 4). Thus, here is the next line of the function: result = (a + b + c + d) / 4; This statement creates a variable called result and calculates the result by adding the four numbers, and then dividing by 4. (The parentheses are necessary to tell JavaScript to perform the addition before the division.) To send this result back to the script that called the function, you use the return keyword. Here is the last part of the function: return result; } Listing 6.3 shows the complete Average() function in an HTML document. This HTML document also includes a small script in the <body> section that calls the Average() function and displays the result. Listing 6.3. The Average() Function in an HTML Document
You can use a variable with the function call, as shown in this listing. This statement averages the numbers 3, 4, 5, and 6 and stores the result in a variable called score: score = Average(3,4,5,6); Did you Know? You can also use the function call directly in an expression. For example, you could use the alert statement to display the result of the function: alert(Average(1,2,3,4)). |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |