450 likes | 538 Views
Functions and Objects. First Midterm exam. Date : October 8, 2008 Content: Two parts: On-paper: Multiple choices On-computer: Write codes Cover everything from Week 1 to Week 5. Working with Functions. Functions allow modular/structure programming
E N D
First Midterm exam • Date: October 8, 2008 • Content: Two parts: On-paper: Multiple choices On-computer: Write codes Cover everything from Week 1 to Week 5
Working with Functions • Functions allow modular/structure programming • Functions encapsulate multiple statements so that these statements can be reused • A function is a block of statements that performs some tasks and/or returns a value • A function is executed when called • Function and method can be used interchangeably
Example • A function to format text before it is written to the page could be reused whenever you desired the same formatting • Example: <script type="text/javascript"> function boldText(incomingText) { var newText = "<b>" + incomingText + "</b>"; return newText; } document.write(boldText("Important Information")); </script>
How to design a Function • Functions should perform only one job, this makes the function more useful • Functions can return a value to the calling statement • In this way functions can be made more flexible by working on many different pieces of data • Functions are encapsulated (self contained) • Functions must have unique names
Function Syntax • Each function must have a unique name, and normally declared in the <head> tag, must be defined before used. • The keyword “function” is used to begin a function definition • Use { } brackets enclose the statement block of a function Syntax of creating a function: function <function name> (<parameters>) { one or more statements } Syntax of calling a function: <function name> (<arguments>)
Parameter Passing • Parameters passed to functions do not necessarily affect the original values of the variables • JavaScript passes variables by “value” and not by “reference to the variable” • Because of this passing by value, local copies of the variables can have different names than the original variables
Parameter Passing Arguments received and stored in local variables. They will disappear when the function ends Arguments passed To receiving function Calling function Receiving function function name (arg1, arg2..) function name (par1, par2..)
Creating a Function In the head: <script type="text/javascript"> function displayInterest ( ) { var interest= simpleInterest( ); if (document.promissoryNote.time.value == 1) { window.alert("Interest after one year is $"+interest+"."); } else { window.alert("Interest after "+document.promissoryNote.time.value+" years is $"+interest+"."); } } Calling function from a javascript
Creating a Function (continued) function simpleInterest() { return document.promissoryNote.principal.value * document.promissoryNote.annualInterestRate.value/100 * document.promissoryNote.time.value; } </script> In the body: <form name="promissoryNote"> Principal: $<input type="text" name="principal"/><p> Annual Interest Rate: <input type="text" name="annualInterestRate"/> %<p> Time: <input type="text" name="time"/> years<p> <input type="submit" value="Calculate Interest" onClick="displayInterest();"/> </form>
Multiple Calls to the Same Function In the head <script type="text/javascript"> function displayInterest( ) { var msg="Cumulative interest. "; var cumInterest=0; for (i=0; i<document.promissoryNote.time.value; i++) { varinterest= simpleInterest(); cumInterest=cumInterest+interest; msg=msg+" Yr "+(i+1)+": $"+cumInterest; } window.alert(msg); }
Multiple Calls to the Same Function(continued) function simpleInterest() { return document.promissoryNote.principal.value * document.promissoryNote.annualInterestRate.value/100; } </script> In the body <form name="promissoryNote"> Principal: $<input type="text" name="principal"/><p> Annual Interest Rate: <input type="text" name="annualInterestRate"/> %<p> Number of Years: <input type="text" name="time"/> years<p> <input type="submit" value="Calculate Interest" onClick="displayInterest();"/> </form>
Passing Parameters <script type="text/javascript"> function displayInterest() { var msg="Cumulative interest. "; var cumInterest=0; for (i=0; i<document.promissoryNote.time.value; i++) { var interest= simpleInterest(); cumInterest=computeCumInterest(cumInterest,interest); msg=msg+" Yr "+(i+1)+": $"+cumInterest; } window.alert(msg); }
Passing Parameters(continued) function computeCumInterest(a,b) { var _interest=a+b; a=a*1000; return _interest; } function simpleInterest( ) { return document.promissoryNote.principal.value * document.promissoryNote.annualInterestRate.value/100; } </script>
Passing Parameters <form name="promissoryNote"> Principal: $<input type="text" name="principal"/><p> Annual Interest Rate: <input type="text" name="annualInterestRate"/> %<p> Number of Years: <input type="text" name="time"/> years<p> <input type="submit" value="Calculate Interest" onClick="displayInterest();"/> </form> Calling function from an event
Calling functions from a link <script type="text/javascript"> function greetings() { document.bgColor ="lightblue"; alert("Greetings to you!"); } <a href="javascript:greetings()"> Click here for Salutation </A> </center> Calling function from a link
Variable Scope in Functions • Variables in functions have meaning either globally or locally • Global variables are created outside any functions • Local variables are created inside a function • Global or local variables can be referenced or altered inside functions
Example <script language=javascript> var name="William"; var hometown ="Chico"; function greetme() { var name="Daniel"; document.bgColor="cyan"; document.write("<h2> In function, <em> name </em> is "+name); document.write(" and <em> hometown </em> is "+hometown); } greetme(); document.write("<h2> Out of the function, <em> name </em> is "+name); document.write(" and <em> hometown </em> is "+hometown); </script> Global variables Local variable
Return a value • A return can be used to send back the results of some tasks • The returned value then can be assigned to a variable if the call to the function is a part of an expression
Summary • Functions allow for the re-use of code • Functions must begin with the keyword “function” • Parameters can be passed to functions to be acted upon • Functions can return (pass back) values to the calling statement • Functions are an excellent way of validating data in an HTML form before sending the form to the server • Functions can be called multiple times • Variables have different scopes inside and outside of functions
Advantages of Functions • Promote good application design • Because they move discrete chunks of script logic into re-usable modules • Modules can be one or more times • Provide a library of modules that can be used in more than one program or page • Reduces the amount of time required to create scripts • Reduces the amount of time required to test and debug scripts
Lab Step 1: Copy and paste (or type) this code <html> <head> <title> Practice debugging Javascript </title> <script type="text/javascript"> function addem() { var n=2; var y=3; document.write(n+y,"<br>"); } </script> </head> <body bgcolor=red> <a href="javascript.addem()"> Click here </a> <H2> Hello </H2> </body> </html>
Lab Step 2: Run this code. What is wrong? Please fix it. Step 3: Modify the script by adding a function called changeColor ( ). This function will take one parameter: a color. Its function is to change the background color of the current document to the given color
Lab Step 4: Modify the body of the existing HTML file to add a form, which looks like: When a user click on the left button, the background is changed to yellow. When a user clicks on the right button, the background is changed to light green
Objects • Work with JavaScript objects • Create user-defined objects
Working With Objects • JavaScript is an object based language • Objects encapsulate variables called properties • These properties can be changed by a script • Objects can contain methods as well as properties • Methods are used to extend the functionality of the object
Using the Object Constructor • Syntax:function objectname(parameters){ this.detail = reference; …..} • Example:function customerInformation(custName, custAddress, custCity, custState, custZip) { this.customerName = custName; this.customerAddress = custAddress; this.customerCity = custCity; this.customerState = custState; this.customerZip = custZip;} • Advantage • Used for compatibility with older browsers
Accessing Object Properties and Methods • Syntax:object.<property name>object.<method name> (<arguments>) • Example:window.name – returns the name of the current windowwindow.open() – opens a new browser window
Example of object properties <script type=“text/javascript”> var.pet =new Object(); pet.cat = new Object(); pet.cat,name=“Friend”; pet.cat.color=“yellow”; pet.cat.size=“medium”; </script> pet cat Friend Yellow Medium
Example of object methods <script type=“text/javascript”> var.pet =new Object(); pet.cat = new Object(); pet.cat,name=“Friend”; pet.cat.color=“yellow”; pet.cat.size=“medium”; function changeSize() { pet.cat.size=“fat” } </script> pet cat Friend Yellow Medium
Creating a User-Defined Object <script type="text/javascript"> function checkDetails() { customer=new Object(); customer.firstName =document.customerAccount.firstName.value; customer.lastName=document.customerAccount.lastName.value, customer.zip=document.customerAccount.zip.value; window.alert("Dear "+customer.firstName+" "+customer.lastName+", you are eligible to enroll for Internet Banking."); } </script>
Creating a User-Defined Object(continued) <form name="customerAccount"> First Name: <input type="text" name="firstName"/><p> Last Name: <input type="text" name="lastName"/><p> Zip: <input type="text" name="zip"/><p> <input type="submit" value="Verify Details" onClick="checkDetails();"/> </form> </html>
Creating an Object Method function checkDetails() { customer=new Object(); customer.firstName =document.customerAccount.firstName.value; customer.lastName=document.customerAccount.lastName.value, customer.zip=document.customerAccount.zip.value; if(verifyZip(customer.zip)) { window.alert("Dear "+customer.firstName+" "+customer.lastName+", you are eligible to enroll for Internet Banking."); } else { window.alert("Dear "+customer.firstName+" "+customer.lastName+", you are not eligible to enroll for Internet Banking."); } }
Creating an Object Method(continued) function verifyZip(zip) { if (zip<23228) { return true; } else { return false; } } </script>
Creating an Object Method(continued) <form name="customerAccount"> First Name: <input type="text" name="firstName"/><p> Last Name: <input type="text" name="lastName"/><p> Zip: <input type="text" name="zip"/><p> <input type="submit" value="Verify Details" onClick="checkDetails();"/> </form> </body> </html>
Summary • Objects have properties and methods • Object properties can be manipulated • Objects can be created using an instantiation process or by using the Object constructor • JavaScript allows for User-Defined objects
Which of the following is required in HTML to use JavaScript? <head> <body> <script> <java>
Matching I.JavaScript A. Http://www.prenhall.com/ II. Java B. allows clients to request a page III. URL C. object-based IV. HTTP D. object-oriented V. Variable E. Occur when something is happened VI. Event-handling F. Data can be stored there
Choices 3. What does this mean: if (is_ie5up || is_nav4)? A. If both, is_ie5up and is_nav4 are true. B. If neither, is_ie5up and is_nav4 are true. C. If, is_ie5up or is_nav4 are true D. All of the above.
Choices What type of variable is ourCustomer in the following code: var ourCustomer=”true”;? a. Boolean b. Null. c. Number d. String
Choices An "if" statement without an "else" includes statements for which of the following? a. Logic for neither the true or false piece. b. Logic for only the true piece. c. Logic for only the false piece. d. Logic for both the true and false piece.
Choices Which of the following is the CORRECT syntax for an if statement? A. if annualIncome < 5000 B. if annualIncome < 5000; C. if (annualIncome < 5000) D. if (annualIncome < 5000);
Choices What is the minimum number of values that can be returned in a function? A. 0 B. 1 C. 2 D. 3
Choices What is TRUE in the following statement: var interest = simpleInterest (int, rate); ? A. The function has no return values or parameters. B. The function has only a return value. C. The function has only parameters. D. The function has a return value and parameters.