1. Trang chủ
  2. » Công Nghệ Thông Tin

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

9 250 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 9
Dung lượng 869,12 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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 lef

Trang 1

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.

F O RM A T

return;

return expression;

E X A M P L E

function sum (a, b) {

var result= a + b;

return result;

}

Trang 2

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>

E X P L A N A T I O N

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)

Trang 3

Figure 7.9 The user is asked for input.

Figure 7.10 The number of miles per gallon is returned by the mileage() function.

Trang 4

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

E X A M P L E 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

}

</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>

E X P L A N A T I O N

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.

Trang 5

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

E X A M P L E 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 + "! ";

}

</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

E X P L A N A T I O N

Trang 6

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

</body>

</html>

E X P L A N A T I O N

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

Trang 7

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 (http://www.crockford.com/JavaScript/private.html), “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 http://www.jibbering.com/faq/faq_notes/closures.html.

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

E X A M P L E 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

</script>

Trang 8

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.

Trang 9

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.

Ngày đăng: 04/07/2014, 02:20

TỪ KHÓA LIÊN QUAN