Tải bản đầy đủ (.pdf) (9 trang)

Học JavaScript qua ví dụ part 17 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (869.13 KB, 9 trang )

ptg
7.1 What Is a Function? 153
7.1.2 Return Values
Functions can return values with a return statement. The return keyword is optional and
can only exist within a function. When the return keyword is reached in a function, no
further processing within the function occurs. A return can be used to send back the
result of some task, such as a calculation, or to exit a function early if some condition
occurs. If a function doesn’t have a return statement, it returns the undefined value.
If the call to the function is made part of an expression, the returned value can be
assigned to a variable. In Example 7.6 the sum function is called with two arguments, 5
and 10. The sum function’s return value will be assigned to the variable total.
var total=sum(5, 10);
Figure 7.8 Output from Example 7.5.
FORMAT
return;
return expression;
EXAMPLE
function sum (a, b) {
var result= a + b;
return result;
}
From the Library of WoweBook.Com
ptg
154 Chapter 7 • Functions
EXAMPLE 7.6
<html>
<head><title>Return Value</title>
<script type="text/javascript">
1 function mileage(miles, gas){
2 return miles/gas; // Return the result of the division
}


</script>
</head>
<body bgcolor="lightgreen">
<font face="arial" size="+1">
<div align="center">
<img src="car-wave.gif">
<script type="text/javascript">
3 var distance=eval(prompt("How many miles did you
drive? ", ""));
var amount=eval(prompt("How much gas did you use?", ""));
4 var rate = mileage(distance, amount);
// Return value assigned to rate
5 alert("Your mileage "+ rate +" miles per gallon.\n");
</script>
</div>
</font>
</body>
</html>
EXPLANATION
1 A function called mileage() is defined in this JavaScript program located between
the <head> tags of the document.
2 The return statement sends back to the caller of the function the result of the di-
vision. That returned value will be assigned to the variable, rate, on line 4.
3 The user is asked for input. The number of miles driven and the amount of gas
used are assigned to the variables called distance and amount, respectively (see
Figure 7.9).
4 The mileage() function is called, passing two arguments. Because the mileage()
function is on the right side of the assignment operator (the = sign), whatever is
returned from the function will be assigned to the variable, called rate, on the left
side of the = sign.

5 The alert dialog box displays the value returned from the function: the number of
miles used per gallon (see Figure 7.10).
From the Library of WoweBook.Com
ptg
7.1 What Is a Function? 155
Figure 7.9 The user is asked for input.
Figure 7.10 The number of miles per gallon is returned by the mileage() function.
From the Library of WoweBook.Com
ptg
156 Chapter 7 • Functions
7.1.3 Anonymous Functions as Variables
A function definition can be assigned directly to a variable. The variable is like any other
variable except that its value is a function definition and this variable is used as a refer-
ence to the function. The () is a JavaScript operator, indicating that a function is to be
called. Pay close attention to the use of the () operator in the next example and how it
affects the outcome of the function variable. Later we will use these anonymous func-
tions with event methods as follows:
window.onload = function() {
alert("Welcome");
}
When the Web page has finished loading, the onload event is triggered and JavaScript
will execute the anonymous function statements, in this case an alert box.
EXAMPLE 7.7
<html>
<head><title>Anonymous Function</title>
<script type="text/javascript">
1 var greetings= function(){ // Anonymous function has no name
2 message="Greetings to you! "; // Function definition
3 return message;
}

</script>
</head>
<body>
<big>
<script type="text/javascript">
4 text=greetings;
// greetings is a variable;
// its value is the function definition
document.write(text +"<br />");
5 text=greetings(); // Call function
document.write(text +"<br />");
</script>
</big>
</body>
</html>
EXPLANATION
1 A function without a name, called an anonymous function, is given its definition
between the curly braces. The definition of the function is assigned to the variable
greetings. We can say then that greetings is the name of a variable whose value is a
function definition and that greetings is a reference to the function.
From the Library of WoweBook.Com
ptg
7.1 What Is a Function? 157
2 In the function a variable called message is assigned a string. Rather than using an
alert box to send the message, it will be returned to the caller.
3 The return statement sends the message back to the caller of the function.
4 Notice that in this line we are displaying the value of the variable greetings. The
definition of the function is shown.
5 In this line the variable name is appended with parentheses, the () operator. This
operator causes JavaScript to call greetings as a function and return the result. In

the previous line, without the () operator, the value of the variable, a function def-
inition, is displayed (see Figure 7.11).
Figure 7.11 A variable with an anonymous function as its value
EXAMPLE 7.8
<html>
<head><title>Functions as Variable</title>
<script type="text/javascript">
1 var greetings=function (visitor){
// Function body is assigned to greetings
message="Greetings to you, " + visitor + "! ";
2 return message;
}
</script>
</head>
<body>
<big>
<script type="text/javascript">
3 var salutation=greetings("Elfie");
document.write(salutation + "<br />");
4 var hello = greetings;
// Function variable assigned to another variable
5 var welcome = greetings;
6 document.write(hello("Stranger") +"<br />");
// Call the function
Continues
EXPLANATION
From the Library of WoweBook.Com
ptg
158 Chapter 7 • Functions
7.1.4 Closures

A closure is an a anonymous function defined within another function. When the outer
function exits, it returns a reference to the inner anonymous function, making it possible
to call the inner function via the reference. A closure means that the local variables can
remain accessible to the inner function even when it seems they should have gone out of
scope. The closure causes the variables to hang around until they are no longer needed.
7 document.write(welcome("your Majesty") +
" May I take your coat? </br />");
</script>
</big>
</body>
</html>
EXPLANATION
1 A function definition is assigned to the variable named greetings. This time the
function will take an argument called visitor.
2 The return statement sends back to the caller the value of the message string as-
signed on the previous line .
3 Because the value of the variable greetings is a function definition, to activate the
function, we need to add parentheses to the variable name. Now the variable acts
as a function call.
4 We can assign the greetings variable to another variable. Now hello contains the
function definition. To call the function add parentheses to hello as hello().
5 Now the variable welcome is assigned the name of the function called greetings. To
call the function, we add parentheses: welcome().
6 The value of the variable, hello, is a function definition. To use the variable as a
function call, parentheses are added to its name, and any arguments passed within
the parentheses just as with any ordinary function call, e.g. hello(“Stranger”).
7 The value of the variable, welcome, is a function definition. The function is called
by adding parentheses to the variable name, welcome (see Figure 7.12).
Figure 7.12 Variables used as functions
EXAMPLE 7.8 (CONTINUED)

From the Library of WoweBook.Com
ptg
7.1 What Is a Function? 159
A common use for a closure is to set up the parameters for a function that will be
called at some time in the future. JavaScript’s setTimeout() function is used to set a timer
in your program. The first argument may be a reference to a function that will be called
after some time interval has passed. You will see in future chapters that JavaScript also
uses closures with event handling and information hiding.
Douglas Crawford writes ( “The
pattern of public, private, and privileged members is possible because JavaScript has clo-
sures. What this means is that an inner function always has access to the vars and param-
eters of its outer function, even after the outer function has returned. This is an
extremely powerful property of the language. There is no book currently available on
JavaScript programming that shows how to exploit it. Most don’t even mention it.”
On the other hand, accidentally creating closures can have harmful side effects such
as Internet Explorer memory leaks and reduced efficiency of code. A very detailed article
on both the pros and cons of using closures, written by Richard Cornford, can be found
at />In the following example the outer function is called paint() and the inner function
is anonymous. The paint() function receives two parameters. It then creates a local
string variable called str and assigns the parameter values to it. When paint() exits, those
variables and their values continue to exist even though they seem like they should have
gone out of scope. Why? Because the anonymous function needs access to the variables
in paint() until it has been called and exits.
EXAMPLE 7.9
<html>
<head><title>Closures</title>
<script type="text/javascript">
1 function paint(type, color) {
2 var str = "The " + type + " is " + color; //local variable
3 var tellme = function() { // Anonymous function

document.write("<big>"+str+".</big><br />")
}
4 return tellme;// return a reference to the function
}
</script>
</head>
<body bgColor="lightgreen">
<h2>Testing a closure</h2>
<script type="text/javascript">
5 var say1 = paint("rose","red");/* A reference to the
anonymous is
function is returned */
6 var say2 = paint("sun", "yellow");
7 alert(say1); // See the value in say1 Figure 7.13
8 say1(); // Call the anonymous function
9 say2();
</script>
</body>
</html>
From the Library of WoweBook.Com
ptg
160 Chapter 7 • Functions
EXPLANATION
1 A function called paint() is defined. It takes two parameters: a type and a color.
2 The local variable called str is assigned a string containing the value of type and
color.
3 The variable tellme is a reference to an anonymous function. Defining a function
within another function is called a closure. This function will print the value of
str and a newline when it is called. But it is only defined here. It will not be called
until after the paint() function exits. Even though this function has no local vari-

ables of its own, it reuses the str variable declared in the outer function.
4 The paint() function returns the variable tellme whose value happens to be a ref-
erence to an anonymous function.
5 The returned value, a reference to the anonymous function defined within the
paint() function, is assigned to say1.
6 The returned value, a reference to the anonymous function defined within the
paint() function, is assigned to say2.
7 Let’s look at the value of the variable say1. In the alert box (Figure 7.13) you can
see that the value of say1 is the complete definition for the anonymous function
declared on line 3.
8 By adding parentheses to the reference say1, so that now it is say1(), the anony-
mous function is called and the statement within it is displayed (see Figure 7.14).
9 The variable say2 is also a reference to an anonymous function; say2() calls that
anonymous function.
Figure 7.13 The value of the variables, say1 and say2, is a function definition.
From the Library of WoweBook.Com
ptg
7.1 What Is a Function? 161
7.1.5 Recursion
Definition of recursion:
recursion: See recursion.
This definition says it all! JavaScript sup-
ports recursion. So what is it? Have you
ever taken apart a Russian doll? Open up
the outside doll and there’s another
smaller duplicate doll inside it, take that
one out, and you find another, and so on, until you get down to a tiny doll at the end.
Then when you put them back, you start with the last doll you opened and keep return-
ing each doll until you get back to the first one you opened. A recursive function is a
function that calls itself. It’s a chain of function calls to the same function. The first time

it calls itself is the first level of recursion, the second time is the second level, and so on.
When a function calls itself, execution starts at the beginning of the function, and when
the function ends, the program backs up to where it was when it called the function and
starts executing from that point. Most important, there must be a way to stop the recur-
sion, or it will be infinite, and probably cause the program to crash.
An example often used to describe recursion can be demonstrated with a function to
produce a Fibonacci sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, and so on.
Here is a little bit of history about how this formula was derived.
In the beginning of the 13th century, an Italian mathematician, Leonardo Fibonacci,
was trying to solve the following problem presented at a mathematical competition in
Pisa: How many rabbits would be produced in a year if, beginning with a single pair of
rabbits, every month each pair reproduces a new pair of rabbits, which become produc-
tive when they are one month old, and none of them die, and so on? Fibonacci came up
Figure 7.14 The closure remembers the values of local variables.
From the Library of WoweBook.Com

×