Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions and Objects. First Midterm exam Date: October 8, 2008 Content: Two parts: On-paper:Multiple choices On-computer: Write codes Cover everything.

Similar presentations


Presentation on theme: "Functions and Objects. First Midterm exam Date: October 8, 2008 Content: Two parts: On-paper:Multiple choices On-computer: Write codes Cover everything."— 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: function boldText(incomingText) { var newText = " " + incomingText + " "; return newText; } document.write(boldText("Important Information"));

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 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 ( ) { one or more statements } Syntax of calling a function: ( )

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 passed To receiving function Arguments received and stored in local variables. They will disappear when the function ends Calling function Receiving function function name (arg1, arg2..)function name (par1, par2..)

9 Creating a Function In the head: 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; } In the body: Principal: $ Annual Interest Rate: % Time: years

11 Multiple Calls to the Same Function In the head function displayInterest( ) { var msg="Cumulative interest. "; var cumInterest=0; for (i=0; i<document.promissoryNote.time.value; i++) { var interest= 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; } In the body Principal: $ Annual Interest Rate: % Number of Years: years

13 Passing Parameters 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; }

15 Passing Parameters Principal: $ Annual Interest Rate: % Number of Years: years Calling function from an event

16 Calling functions from a link function greetings() { document.bgColor ="lightblue"; alert("Greetings to you!"); } Click here for Salutation 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 var name="William"; var hometown ="Chico"; function greetme() { var name="Daniel"; document.bgColor="cyan"; document.write(" In function, name is "+name); document.write(" and hometown is "+hometown); } greetme(); document.write(" Out of the function, name is "+name); document.write(" and hometown is "+hometown); 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 Practice debugging Javascript function addem() { var n=2; var y=3; document.write(n+y," "); } Click here Hello

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, cust Address, 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. object. ( ) Example: window.name – returns the name of the current window window.open() – opens a new browser window

29 Example of object properties var.pet =new Object(); pet.cat = new Object(); pet.cat,name=“Friend”; pet.cat.color=“yellow”; pet.cat.size=“medium”; pet cat Friend Yellow Medium

30 Example of object methods 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” } pet cat Friend Yellow Medium

31 Creating a User-Defined Object 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."); }

32 Creating a User-Defined Object (continued) First Name: Last Name: Zip:

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; }

35 Creating an Object Method (continued) First Name: Last Name: Zip:

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?

39 Matching I. JavaScriptA. Http://www.prenhall.com/ II.JavaB. allows clients to request a page III.URLC. object-based IV.HTTPD. object-oriented V.VariableE. Occur when something is happened VI. Event-handlingF. 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.


Download ppt "Functions and Objects. First Midterm exam Date: October 8, 2008 Content: Two parts: On-paper:Multiple choices On-computer: Write codes Cover everything."

Similar presentations


Ads by Google