THINKING BIG Abstraction and Functions chapter 6 Modified by Dr. Paul Mullins for CPSC 130, F05
Copyright © 2003 Pearson Education, Inc. Slide 20-2 ABSTRACTION > Functions for reuse, readability, … > Unique Names — buttons on calculator > Encapsulation — how does it calculate a square root? > Parameterization — enter value, press function button → answer displayed √
Copyright © 2003 Pearson Education, Inc. Slide 20-3 CREATING A JS FUNCTION function average (num1, num2) { // Javascript statements var local = (num1 + num2) / 2; return local; } statements executed when this function is called Unique identifier Parameters: Placeholders for information to be sent to the function Variable created just for this function call Value that will replace the function call
Copyright © 2003 Pearson Education, Inc. Slide 20-4 Figure An HTML page showing the use of the convertC2F() JavaScript function to find the Fahrenheit equivalent of 38°C.
Copyright © 2003 Pearson Education, Inc. Slide 20-5 APPLYING FUNCTIONS > The HTML Page to Host JavaScript > How the convertC2F() Function Runs > The document.write() Function > Applying convertC2F() > Applying convertC2F() Again > Reusing Functions
Copyright © 2003 Pearson Education, Inc. Slide 20-6 Figure An HTML source file containing a JavaScript document.write(), and the HTML text used by the browser to create the page.
Copyright © 2003 Pearson Education, Inc. Slide 20-7 Figure The HTML and JavaScript to display a list of equivalent temperatures.
Copyright © 2003 Pearson Education, Inc. Slide 20-8 Figure 20.3 (continued). The HTML and JavaScript to display a list of equivalent temperatures.
Copyright © 2003 Pearson Education, Inc. Slide 20-9 Figure HTML and JavaScript to produce a table of equivalents.
Copyright © 2003 Pearson Education, Inc. Slide Figure 20.4 (continued). HTML and JavaScript to produce a table of equivalents.
Copyright © 2003 Pearson Education, Inc. Slide JAVASCRIPT RULES FOR FUNCTIONS > Function Declarations: function name ( params ) > Selecting Function Names – meaningful > Parameters – comma separated list of palceholders > Return Values – replace the call in an expression > Scope of Reference – { } > Local Variables – exist only in function, reinitialized > Global Variables – exist “everywhere”, retain value > Multiple Parameters – matched by position in list > Calling Functions – use name() where you want the action or value > Arguments – values to replace params for this call