1 / 45

Functions and Objects

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

Télécharger la présentation

Functions and Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions and Objects

  2. 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

  3. 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

  4. 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>

  5. 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

  6. 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>)

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

  8. 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..)

  9. 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

  10. 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>

  11. 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); }

  12. 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>

  13. 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); }

  14. 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>

  15. 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

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

  21. 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

  22. 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>

  23. 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

  24. 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

  25. Objects • Work with JavaScript objects • Create user-defined objects

  26. 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

  27. 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

  28. 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

  29. 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

  30. 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

  31. 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>

  32. 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>

  33. 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."); } }

  34. Creating an Object Method(continued) function verifyZip(zip) { if (zip<23228) { return true; } else { return false; } } </script>

  35. 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>

  36. 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

  37. Practice exercise

  38. Which of the following is required in HTML to use JavaScript? <head> <body> <script> <java>

  39. 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

  40. 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.

  41. Choices What type of variable is ourCustomer in the following code: var ourCustomer=”true”;? a. Boolean b. Null. c. Number d. String

  42. 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.

  43. 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);

  44. Choices What is the minimum number of values that can be returned in a function? A. 0 B. 1 C. 2 D. 3

  45. 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.

More Related