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

Slides:



Advertisements
Similar presentations
Introducing JavaScript
Advertisements

JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
The Web Warrior Guide to Web Design Technologies
JavaScript 101 Lesson 01: Writing Your First JavaScript.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
HTML Comprehensive Concepts and Techniques Second Edition Project 8 Integrating JavaScript with HTML.
Tutorial 10 Programming with JavaScript
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
CIS101 Introduction to Computing Week 12 Spring 2004.
Lesson15. JavaScript Objects Objects encapsulate data (properties) and behavior(methods); the properties and the methods of an object are tied together.
Javascript fundamentals (continue). Visual Web Developer wd/download/
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
SYST Web Technologies SYST Web Technologies Lesson 6 – Intro to JavaScript.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Arrays – What is it? – Creation – Changing the contents Functions – What is it? – Syntax – How they work – Anonymous functions A quick lesson in Objects.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
Functions and Objects. First Midterm exam Date: 10/10/2006 (Tuesday) Content: Multiple choices Determine results of the code Write codes Covert everything.
Week 9 PHP Cookies and Session Introduction to JavaScript.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
1 JavaScript in Context. Server-Side Programming.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
TUTORIAL 10: PROGRAMMING WITH JAVASCRIPT Session 2: What is JavaScript?
Tutorial 10 Programming with JavaScript. XP Objectives Learn the history of JavaScript Create a script element Understand basic JavaScript syntax Write.
Tutorial 10 Programming with JavaScript
Done by: Hanadi Muhsen1 Tutorial 1.  Learn the history of JavaScript  Create a script element  Write text to a Web page with JavaScript  Understand.
Using Client-Side Scripts to Enhance Web Applications 1.
Keeping it Neat: Functions and JavaScript Source Files Chapter 7.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (there is an audio component to this eLesson) © Dr.
CPS120: Introduction to Computer Science Lecture 14 Functions.
JavaScript III Functions and Abstraction. 2 JavaScript so far statements assignment function calls data types numeric string boolean expressions variables.
XP Tutorial 10New Perspectives on HTML and XHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
Introduction to JavaScript CS101 Introduction to Computing.
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
XP Tutorial 8 Adding Interactivity with ActionScript.
JavaScript, Fourth Edition
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
1 JavaScript in Context. Server-Side Programming.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
Functions Function is a standalone block of statements that performs some tasks and returns a value. Functions must be declared before they can be used.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
JavaScript 101 Lesson 6: Introduction to Functions.
JavaScript and AJAX 2nd Edition Tutorial 1 Programming with JavaScript.
JavaScript Tutorial First lecture 19/2/2016. Javascript is a dynamic computer programming language. It is lightweight and most commonly used as a part.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
“Under the hood”: Angry Birds Maze
Tutorial 10 Programming with JavaScript
JavaScript is a programming language designed for Web pages.
JavaScript Syntax and Semantics
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
PHP.
Functions, Regular expressions and Events
JavaScript What is JavaScript? What can JavaScript do?
Tutorial 10 Programming with JavaScript
JavaScript What is JavaScript? What can JavaScript do?
Tutorial 10: Programming with javascript
JavaScript Basics What is JavaScript?
JavaScript is a scripting language designed for Web pages by Netscape.
CIS 136 Building Mobile Apps
Web Programming and Design
SEEM 4540 Tutorial 4 Basic PHP based on w3Schools
Presentation transcript:

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 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: function boldText(incomingText) { var newText = " " + incomingText + " "; return newText; } document.write(boldText("Important Information"));

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 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: ( )

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

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

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

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

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

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

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

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

Calling functions from a link function greetings() { document.bgColor ="lightblue"; alert("Greetings to you!"); } Click here for Salutation 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 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

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 Practice debugging Javascript function addem() { var n=2; var y=3; document.write(n+y," "); } Click here Hello

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

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

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

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

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

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

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

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

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

Practice exercise

Which of the following is required in HTML to use JavaScript?

Matching I. JavaScriptA. 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

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.