Chapter 10 Java Script Functions CIS 275Web Application

Chapter 10: Java. Script Functions CIS 275—Web Application Development for Business I

Program Modules in Java. Script n n n n Software development is best achieved in smaller pieces called _____, applying the principle of “divide and conquer”. A module in Java. Script is called a _____. A pre-defined function that belongs to a class is called a method (like Math. pow or Math. round). A function you write is called a ______defined function. A function is invoked by a function call. A function call may include arguments. A called function may _______ data to the caller. 2

Programmer-Defined Functions n n All variables declared in a function are _______. A function declaration may include parameters, which are also local variables. Functions enable the principle of software reuse and help to avoid code repetition. Format of a function definition function-name ( parameter-list ) { declarations and statements } n n () is the function call operator. The ___ The first line is the function declaration and the content within the {}’s is the function ______. 3

Fig. 10. 2 <html xmlns = "http: //www. w 3. org/1999/xhtml"> <head> <title>A Programmer-Defined Function</title> <script type = "text/javascript"> document. writeln( "<h 1>Square numbers from 1 to 10</h 1>" ); for ( var x = 1; x <= 10; ++x ) document. writeln( "The square of " + x + " is " + square( x ) + " " ); function square( y ) // do NOT use var here { return y * y; } </script> </head> <body></body> </html> 4

Example of a Function Call <html> <head> <script type="text/javascript"> function my. Function(){ alert("HELLO") } </script> </head> <body> <form> <input type = "button" onclick = "my. Function()" value = "Call function" > </form> <p>By pressing the button, a function will be called. The function will alert a message. </p> </body> </html> 5

Function Call w/ Arguments and Return <? xml version = "1. 0"? > <!DOCTYPE html PUBLIC "-//W 3 C//DTD XHTML 1. 0 Strict//EN" "http: //www. w 3. org/TR/xhtml 1/DTD/xhtml 1 -strict. dtd"> <html> <head> <script type="text/javascript"> function total(number. A, number. B){ return number. A + number. B } </script> </head> <body> <script type="text/javascript"> document. write( total(2, 3) ) </script> </body> </html> 6

10. 8 Scope Rules n n n The scope of an identifier for a variable or function is the part of the program in which the identifier can be referenced. Variables declared in the ______ element are global variables and have global scope. Variables declared inside a function have ______ scope and can be used only in that function. Function parameters also have local scope. A variable with local scope will ______ a variable with the same name that has global scope. 7
- Slides: 7