The function keyword is followed by the user-defined name of the function called welcome and a set of parentheses.. Figure 7.1 After the function welcome is called, output is sent to th
Trang 1143
7
Functions
7.1 What Is a Function?
A pocket calculator performs certain functions You push the buttons, send information
to the calculator, it performs a calculation, and sends back the results You don’t care
about what transpires inside the calculator, you just want the results That’s what a
func-tion does Funcfunc-tions are self-contained units of a program designed to accomplish a
specified task such as calculating mortgage payments, displaying random images, or
checking for valid input They can be used over and over again and thus save you from
repetitious programming They are also used to break up a program into smaller
mod-ules to keep it better organized and easier to maintain JavaScript has a large number of
its own built-in functions, and now you can create your own
By definition, a function is a block of statements that not only performs some task,
but also returns a value A function is an independent part of your program and not
exe-cuted until called A function is often referred to as a “black box.” It’s like the pocket
calculator: Information goes into the black box (or calculator) as input and the action
or value returned from the box is its output What goes on inside the box is transparent
to the user The programmer who writes the function is the only one who cares about
those details When you use document.write(), you send something like a string of text
to the function, and it sends some text back to the browser You don’t care how it does
its job, you just expect it to work If you send bad input, you get back bad output or
maybe nothing, hence the expression “Garbage in, garbage out.”
Functions are like miniscripts They contain JavaScript statements that behave as a
single command and can be called repeatedly throughout a program without rewriting
the code
The terms “function” and “method” are often used interchangeably A method refers
to a function that is used with JavaScript objects (covered in Chapter 8, “Objects”) A
function, as used in this chapter, is a stand-alone block of statements, independent of
the program until invoked by a caller
Trang 27.1.1 Function Declaration and Invocation
Functions must be declared before they can be used Normally functions are placed in
the <head> tag of the HTML document to ensure that they are defined before used
Within the <script> tag itself, they can go anywhere Function definitions are often
stored in external JavaScript files or libraries (see “JavaScript from External Files” on
page 22 of Chapter 1)
To define a function, the function keyword is followed by the name of the function
and a set of parentheses The parentheses are used to hold parameters, values that are
received by the function The function’s statements are enclosed in curly braces
function bye() { document.write ("Bye, adios, adieu, au revoir "); }
Once you define a function, you can use it JavaScript functions are invoked by
call-ing the function; for example, bye() A function can be called directly from within the
<script> tag, from a link, or when an event is triggered, such as when the user presses a
key When called, the function’s name is followed by a set of parentheses that may
con-tain messages that will go to the function These messages are called arguments
To check whether the function has been defined or if it is truly a function, use the
typeof operator; for example, typeof(function_name).
F O RM A T
Function definition:
function function_name () {statement; statement;}
function function_name (parameter, parameter){statement; statement;}
Function call:
function_name();
function_name(argument1, argument2, )
E X A M P L E 7 1
<html>
<head><title>A Simple Function</title>
<script type="text/javascript">
1 function welcome(){ // Function defined within <head> tags
2 var place="San Francisco";
3 alert("Welcome to "+ place + "!");
</script>
</head>
Trang 3<body bgcolor="lightblue">
<big>
<div align="center">
<script type="text/javascript">
</script>
<b>San Francisco</b><br />
6 <img src="sf.jpg" width="400" height="300" border="1">
</div>
</big>
</body>
</html>
E X P L A N A T I O N
1 Functions must be defined before they can be used Therefore, functions are
nor-mally placed in a JavaScript program, between the HTML <head></head> tags In
this example, the function is defined, but it will not do anything until it is called
from somewhere in the file
The function keyword is followed by the user-defined name of the function called
welcome and a set of parentheses The parentheses are used to hold parameters,
information being received by the function What the function actually does is
de-fined in a set of statements enclosed within curly braces The function statements
are enclosed in a set of curly braces
2, 3 This is the code that is run whenever the function is called It is called the
func-tion definifunc-tion When this funcfunc-tion is called, the string San Francisco will be
as-signed to the variable called place and the alert dialog box will display “Welcome
to San Francisco!” in the browser window (see Figure 7.1).
4 This is the final closing curly brace that ends the function definition
5 This is where the function is invoked or called When the function welcome() is
called, the statements within its definition will be executed
6 The function is defined in the head of the document and called from the body of
the document before the <img> tag is reached This image will not appear until the
user clicks the OK button in the alert dialog box (see Figure 7.2)
Figure 7.1 After the function welcome() is called, output is sent to the browser.
E X A M P L E 7 1 (C O N T I N U E D)
Trang 4Passing Arguments. If a user wants to send values to a function, the values are
enclosed in the parentheses right after the function name and sent as a comma-separated
list of arguments when the function is called The arguments are received by the
func-tion in a list of corresponding values called parameters (see Figure 7.3) The names of
the arguments are not necessarily the same names in the parameter list, but they
corre-spond to the same values These values can be assigned to local variables within the
function Local variables disappear when the function exits JavaScript doesn’t keep
track of the number of arguments sent to the function to make sure they match up with
the number of parameters specified in the function definition at the other end If you
send three arguments, and there are only two parameters defined within the function,
the third argument is ignored If you send three arguments, and there are four
parame-ters waiting within the function, then the fourth parameter is undefined It’s similar to
sending messages to an answering machine If you send a message and the message
machine is full, your message is ignored, and if you send a message and there’s room for
more messages, the message you sent is stored, and the unused space is still there, but not
defined
function_name(argument1, argument2, ); // function call (caller)
function_name(parameter1, parameter2 ){ // function definition (receiver)
var result= parameter1 + parameter2;
} // curly braces required
Figure 7.2 After the user clicks the OK button in the alert box, this image loads.
Trang 5Figure 7.3 In the analogy of the pocket calculator, you are the caller when you
press the buttons, and the internal functions inside the calculator are the receiver.
E X A M P L E 7 2
<html>
<head><title>Passing Arguments</title>
<script type="text/javascript">
1 function greetings(pal){ // "Birdman!" is stored in pal
2 alert("Greetings to you, " + pal);
}
</script>
</head>
<body background="birdman.jpg">
3 <script type="text/javascript">
4 greetings("Birdman!"); // Passing an argument
</script>
</body>
</html>
E X P L A N A T I O N
1 The function, greetings(), has one parameter, called pal This parameter holds a value
that is sent to the function when it was called The parameter name is any valid
Java-Script variable name At this point, the function has been defined but not called
2 The alert method will display the string, “Greetings to you, ” concatenated to the
value stored in pal; in this example that value is “Birdman!”.
3 The JavaScript program is in the body of the document It contains a function call
that will invoke a function defined in the head of the document
4 The function greetings() is called with one argument, “Birdman!” This argument
will be sent to the function, and assigned to the parameter, pal If the function had
been called in the head of the document as it was in Example 7.1, the background
image would not appear until after the user clicks the OK button in the alert box
(see Figure 7.4), but in this example, the image was loaded before the function
was called
Arguments are received
as parameters by the receiving function and stored in local variables;
they will disappear when the function ends.
Arguments are
passed to the
receiving function.
Trang 6Calling a Function from a Link. A function can be called directly from a link, by
using the JavaScript pseudoprotocol, JavaScript:, instead of a normal URL The
Java-Script: protocol and the function call are placed within quotes and assigned to the href
attribute of the <a> tag When the user clicks his or her mouse on the link, instead of
the program going to the URL of another page, a JavaScript function will be called
Figure 7.4 Output from the greetings() function in Example 7.2.
E X A M P L E 7 3
<html>
<head><title>Functions</title>
1 <script type="text/javascript">
2 function greetings(){ // Function defined within <head> tags
document.bgColor="lightblue";
alert("Greetings to you!");
</script>
</head>
<body bgcolor="silver">
<div align="center">
4 <a href="JavaScript:greetings()"><big>Click here for
Salutations</big>
</a><br />
</div>
</body>
</html>
Trang 7Calling a Function from an Event. An event is triggered when a user performs
some action, like clicking a button or moving the mouse over a link The function
assigned to the event is called an event handler When the event is triggered, the
func-tion is called In the following example, when the user clicks the Welcome button, the
function is called
E X P L A N A T I O N
1 The JavaScript program starts here in the head of the document The function is
defined within the head of the document to guarantee that it will be defined
be-fore being called
2, 3 The function greetings() is defined It is very simple It causes the background
col-or of the document to be a light blue colcol-or and causes an alert box to appear with
a greeting message
4 The href attribute of the link tag is assigned a string consisting of the JavaScript:
pseudoprotocol, followed by the name of the function to be called When the user
clicks this link, JavaScript calls the function, greetings() (See Figure 7.5.)
Figure 7.5 After clicking the link, the function is called, causing the alert dialog box
to appear.
E X A M P L E 7 4
<html>
<head><title>Functions and Events</title>
<script type="text/javascript">
1 function greetings(you){ // Function definition
2 document.bgColor="lavender";
alert("Greetings and Salutations! " + you);
}
</script>
</head>
Continues
Trang 83 <body>
<div align="center">
4 <form>
5 <input type="button"
6 value="Welcome button"
7 onClick="greetings('Dan');"
/>
</form>
</div>
</body>
</html>
E X P L A N A T I O N
1 The JavaScript program starts here The function is defined in the head of the
doc-ument
2 The function greetings() is defined here.
3 The body of the page starts here
4 An HTML form starts here It will be used to create a button input device
5 The type of input device is a button
6 The value that will be displayed in the button is “Welcome button” (see Figure 7.6).
7 When the user presses or clicks the button, the onClick event handler will be
trig-gered, causing the greetings() function to be called The value assigned to the
on-Click event handler is a JavaScript function enclosed in quotation marks (see
Fig-ure 7.7)
Figure 7.6 When the button is clicked, the event is triggered.
E X A M P L E 7 4 (C O N T I N U E D)
Trang 9Calling a Function from JavaScript. In the first examples of this chapter,
func-tions were defined in one JavaScript script and called from another Although it is valid
to define and call the function from the same JavaScript program, it is often desirable to
define the function in the head of the document, to be sure it has been defined before it
is called Then you can call the function from a link, an event, or another JavaScript
pro-gram Because the document is defined within the <body></body> tags, the body is often
the place from where you will call functions The general rule of thumb is: If your script
is designed to write data to the page, put the <script></script> tags within the
<body></body> tags Example 7.2 called a function from one JavaScript program within
the body, but defined the function in another JavaScript program within the head
Finally, you might want to store function definitions in an external library (.js file)
where they can be reused and shared by other programs
Scope of Variables in Functions. The scope of a variable describes where the
vari-able is visible in the program; that is, where it can be used in the program Varivari-ables
declared outside of functions are global in scope, meaning they can be used or changed
anywhere in the program A variable is also global if declared within a function unless
it is declared within a function with the var keyword The var keyword makes the
vari-able local in scope; that is, the varivari-able can be used only within the function where it is
defined and is no longer visible once the function ends
Figure 7.7 A function is called after the event is triggered The function “handles”
the event.
Trang 10E X A M P L E 7 5
<html>
<head><title>Function Scope</title>
<script type="text/javascript">
1 var name="William"; // Global variable
var hometown="Chico";
3 var name="Daniel"; // Local variable
var hometown="Husingen";
4 alert("In function the name is " + name +
" and hometown is "+ hometown);
</script>
</head>
<body>
<script type="text/javascript">
7 alert("Out of function, name is "+ name +
8 " and hometown is " + hometown);
</script>
</body>
</html>
E X P L A N A T I O N
1 The variables called name and hometown are global in scope They are visible
throughout the JavaScript program
2 The function called greetme() is declared and defined.
3 Any variables declared within a function with the var keyword are local to that
function In fact, you must use the var keyword when declaring local variables;
otherwise, the variables will be global The variable called name has been declared
inside the function This is a local variable and has nothing to do with the global
variable of the same name on line 1 The function variable will go out of scope;
that is, it will no longer be visible, when the function ends on line 6, at which
point the global variable will come back in scope If the variable, name, had been
given a different name, within the function, such as name2 or myName, then the
global variable would have remained in scope within the function
4 The variable called name and hometown were defined inside this function and are
local in scope They will stick around until the function exits
5 The closing curly brace marks the end of the function definition
6 The function greetme() is called here.
7 The global variable called name has come back into scope.
8 The global variable called hometown is still in scope (see Figure 7.8).