Download presentation
Presentation is loading. Please wait.
Published byKathryn Townshend Modified over 10 years ago
1
Project 7: Understanding Functions Essentials for Design JavaScript Level One Michael Brooks
2
Copyright (c) 2004 Prentice-Hall. All rights reserved. 2 Objectives Use a simple function Pass information to a function Return information from a function
3
Copyright (c) 2004 Prentice-Hall. All rights reserved. 3 Objectives (continued) Use a function in an external file Use local and global scope variables Implement object inheritance and properties Create a custom method for a custom object
4
Copyright (c) 2004 Prentice-Hall. All rights reserved. 4 Why Would I Do This? A function: Is simply a block of code that can be named and reused repeatedly Is often defined in the head section of the HTML document Can also be stored in an external file, for situations where we want to share it among multiple Web pages
5
Copyright (c) 2004 Prentice-Hall. All rights reserved. 5 Why Would I Do This? (continued) You can think of a function as a method you can create You can call the function by name to invoke it Depending on what you've designed the function to do: You can pass it information It may complete some action or actions It may return information back to you
6
Copyright (c) 2004 Prentice-Hall. All rights reserved. 6 Visual Summary Functions are created by declaring them using the function keyword followed by a name for the function Instructions for the function to execute are included in a code block Example
7
Copyright (c) 2004 Prentice-Hall. All rights reserved. 7 Visual Summary (continued) function declaration variable created to hold info passed to function code block starts code block ends function is invoked information is passed to function
8
Copyright (c) 2004 Prentice-Hall. All rights reserved. 8 Visual Summary (continued) Functions are an important part of an object oriented environment Functions are essentially methods which we can create and reuse By using more advanced techniques, we can create custom objects using functions
9
Copyright (c) 2004 Prentice-Hall. All rights reserved. 9 Use a Simple Function Functions: Are normally created in the head section of an HTML document Can placed anywhere in the document or even in external files Consists solely of the: keyword function the name of the function a code block of commands to be executed when the function is called
10
Copyright (c) 2004 Prentice-Hall. All rights reserved. 10 Use a Simple Function (continued) It is often useful to use a function to perform an action when an event occurs Event handlers can be used for this purpose function addThem() { var total=2+3; document.write(total); } Add the numbers
11
Copyright (c) 2004 Prentice-Hall. All rights reserved. 11 Use a Simple Function (continued) Create a Simple Function in the Head of the Document You can create a simple function in the head section of an HTML document This is: the most common place for functions to appear the preferred place to create functions for most Web developers Example Example
12
Copyright (c) 2004 Prentice-Hall. All rights reserved. 12 Use a Simple Function (continued) simple.html function sayHello() { alert("Hello"); } sayHello(); Declaring the function Calling the function The result of calling the function
13
Copyright (c) 2004 Prentice-Hall. All rights reserved. 13 Use a Simple Function (continued) Create a Simple Function in the Body of the Document You can create a function in the body of the document Although less common, this is perfectly acceptable under modern ECMAScript standards Example
14
Copyright (c) 2004 Prentice-Hall. All rights reserved. 14 Use a Simple Function (continued) simple.html sayHello(); function sayHello() { alert("Hello"); } Calling the function Declaring the function The result of calling the function
15
Copyright (c) 2004 Prentice-Hall. All rights reserved. 15 Use a Simple Function (continued) Invoke a Function Using an Event Handler You can use an event handler to invoke a function Most practical examples of useful functions require some user action such as: the submission of a form the rolling over of an image the press of a hyperlink Example Example
16
Copyright (c) 2004 Prentice-Hall. All rights reserved. 16 Use a Simple Function (continued) event.html function sayHi() { document.write("Hi "); } click here to say Hi! Declaring the function Calling the function The result of calling the function
17
Copyright (c) 2004 Prentice-Hall. All rights reserved. 17 Pass Information to a Function It is often useful to pass information to a function This can be done in the same way that information is passed to methods The function would need a receptacle for storing the information being passed to the function This can be done by creating a variable function createWindow(page) { window.open(page); }
18
Copyright (c) 2004 Prentice-Hall. All rights reserved. 18 Pass Information to a Function (continued) The information could also be passed to the function using a variable value The interpreter will still pass the information as before URL="http://www.againsttheclock.com"; createWindow(URL);}
19
Copyright (c) 2004 Prentice-Hall. All rights reserved. 19 Pass Information to a Function (continued) Send A Text String to a Function You can pass a text string to a function Like methods, functions may or may not have arguments passed to them the function definition will determine how many pieces of information are sent to the function Example
20
Copyright (c) 2004 Prentice-Hall. All rights reserved. 20 Pass Information to a Function (continued) whisper.html function whisper(info) { document.write(info.toLowerCase()+" "); } whisper("HELLO CLEVELAND!"); The result of calling the function
21
Copyright (c) 2004 Prentice-Hall. All rights reserved. 21 Pass Information to a Function (continued) Send Variable Information to a Function You can pass variable information to a function in the form of a string value It is also acceptable to send: boolean values numbers other types of variable information Example Example
22
Copyright (c) 2004 Prentice-Hall. All rights reserved. 22 Pass Information to a Function (continued) whisper.html function whisper(info) { document.write(info.toLowerCase()+" "); } myString="HEY MAN!"; whisper(myString); The result of calling the function
23
Copyright (c) 2004 Prentice-Hall. All rights reserved. 23 Pass Information to a Function (continued) Send Multiple Values to a Function You can pass multiple pieces of information to a function to complete a calculation Example Example
24
Copyright (c) 2004 Prentice-Hall. All rights reserved. 24 Pass Information to a Function (continued) volume.html function determineVolume(theLength,width,height) { volume=theLength*width*height; document.write("The volume is "+volume); } theLength=100; width=20; height=5; determineVolume(theLength,width,height); The result of calling the function passing multiple pieces of information
25
Copyright (c) 2004 Prentice-Hall. All rights reserved. 25 Pass Information to a Function (continued) Test A Function Trigger You can: create a function use an online event to test the function to make sure it was being triggered properly Example Example
26
Copyright (c) 2004 Prentice-Hall. All rights reserved. 26 Pass Information to a Function (continued) tax.html function computeTax() { alert("function is triggered!"); } // end function Tax rate is 6.5% Purchase amount is $1,000 Compute tax amount The result of calling the function using an event handler
27
Copyright (c) 2004 Prentice-Hall. All rights reserved. 27 Pass Information to a Function (continued) Send Information from Inline Events You can pass multiple pieces of information to functions when an event was detected Example Example
28
Copyright (c) 2004 Prentice-Hall. All rights reserved. 28 Pass Information to a Function (continued) tax.html function computeTax(purchaseAmount,taxRate){ taxAmount=purchaseAmount*taxRate; document.write("Tax amount is "+taxAmount); } // end function Tax rate is 6.5% Purchase amount is $1,000 Compute tax amount The result of calling the function
29
Copyright (c) 2004 Prentice-Hall. All rights reserved. 29 Return Information from a Function Functions may or may not return values The keyword, return, can be used to tell JavaScript to return data to the statement that called the function function computeTax(amount) { var tax=amount*.06; return tax; }
30
Copyright (c) 2004 Prentice-Hall. All rights reserved. 30 Return Information from a Function Functions may or may not return values The keyword, return, can be used to tell JavaScript to return data to the statement that called the function Example Example function computeTax(amount) { var tax=amount*.06; return tax; }
31
Copyright (c) 2004 Prentice-Hall. All rights reserved. 31 Return Information from a Function (continued) random.html function makeRandom() { randomNumber=Math.random(); return randomNumber; } // end function document.write(" "+makeRandom()+" "); The result of calling the makeRandon () function
32
Copyright (c) 2004 Prentice-Hall. All rights reserved. 32 Return Information from a Function (continued) Assign Function Results to a Variable You can assign function results to a variable Data from functions can be assigned to variables in the same way that data from methods can be assigned to variables Example Example
33
Copyright (c) 2004 Prentice-Hall. All rights reserved. 33 Return Information from a Function (continued) random.html function makeRandom() { randomNumber=Math.random(); return randomNumber; } // end function myNumber=makeRandom(); document.write(" "+myNumber+" "); The result of calling the makeRandon () function by assigning function results to a variable
34
Copyright (c) 2004 Prentice-Hall. All rights reserved. 34 Use a Function in an External File JavaScript allows the placement of functions in external files The ability to place JavaScript functions in external files can be very useful: It further eliminates the need for redundant code by eliminating the need for multiple pages to declare the same functions It allows multiple pages or even multiple Web sites to share functions
35
Copyright (c) 2004 Prentice-Hall. All rights reserved. 35 Use a Function in an External File (continued) Functions are the only type of JavaScript code that can be placed in an external file External JavaScript files are simply text files, like HTML files, and can be created in any text editor Functions in external files can often be shared among different languages, especially if the languages are ECMAScript compliant
36
Copyright (c) 2004 Prentice-Hall. All rights reserved. 36 Use a Function in an External File (continued) Most developers use a.js file extension to name an external JavaScript file but this is not required by the interpreter Any text file with valid functions will work for this purpose, despite the filename and extension Functions in external files are linked using the src attribute of the tag
37
Copyright (c) 2004 Prentice-Hall. All rights reserved. 37 Use a Function in an External File (continued) Create an External JavaScript Code File You can create an external JavaScript code file, using the.js file extension in any text editor
38
Copyright (c) 2004 Prentice-Hall. All rights reserved. 38 Use a Function in an External File (continued) Link External Files to HTML Documents You can create JavaScript code that is placed in an external file You can also create a link to an HTML file that would make the functions available in that document Example Example
39
Copyright (c) 2004 Prentice-Hall. All rights reserved. 39 Use a Function in an External File (continued) external.html The result of using an external file
40
Copyright (c) 2004 Prentice-Hall. All rights reserved. 40 Use Local and Global Scope Variables The scope of a variable defines where a variable can be used in a script Variables defined (or declared) outside of functions are global in scope This means they can be used or changed anywhere in the script Variables with global scopes are known as global variables
41
Copyright (c) 2004 Prentice-Hall. All rights reserved. 41 Use Local and Global Scope Variables (continued) Variables declared within a function using the var keyword are local in scope Variables that have a local scope can only be used within the function where they are created Local scope variables are known as local variables
42
Copyright (c) 2004 Prentice-Hall. All rights reserved. 42 Use Local and Global Scope Variables (continued) Variables created outside of functions have a global scope Variables created inside functions with the var keyword have a local scope only and are inaccessible outside the function Variables created inside functions without using the var keyword have a global scope
43
Copyright (c) 2004 Prentice-Hall. All rights reserved. 43 Use Local and Global Scope Variables (continued) Variables created inside functions without using the var keyword have a global scope Variables with a local scope will override the global scope variables within a function The variable ceases to exist when: the function is complete the global variable with the same name then becomes accessible again
44
Copyright (c) 2004 Prentice-Hall. All rights reserved. 44 Use Local and Global Scope Variables (continued) Use a Local Scope Variable It is possible to have local and global scope variables with the same name Examples
45
Copyright (c) 2004 Prentice-Hall. All rights reserved. 45 Use Local and Global Scope Variables (continued) scope.html function myFunc() { a=32; document.write("In the function the variable value is "+a+" ");} myFunc(); document.write("Outside the function, the variable value is "+a); Example of using a local scope variable Next
46
Copyright (c) 2004 Prentice-Hall. All rights reserved. 46 Use Local and Global Scope Variables (continued) scope.html function myFunc() { document.write("In the function the variable value is "+a+" ");} myFunc(); document.write("Outside the function, the variable value is "+a); An error appears since the variable is inaccessible outside of the function
47
Copyright (c) 2004 Prentice-Hall. All rights reserved. 47 Use Local and Global Scope Variables (continued) Distinguish Between Local and Global Scope Variables It is very important to distinguish between local and global scope variables Any variable created with the var keyword in a function is inaccessible outside the function Example
48
Copyright (c) 2004 Prentice-Hall. All rights reserved. 48 Use Local and Global Scope Variables (continued) scope.html function myFunc() { a=32; document.write("In the function the variable value is "+a+" ");} // create a global variable var a=10; myFunc(); document.write("Outside the function, the variable value is "+a); Example of using Local and Global Scope Variables
49
Copyright (c) 2004 Prentice-Hall. All rights reserved. 49 Use Custom Objects and Properties A class: Is the definition of the object including the properties, methods and events available to the object Is usually created by a constructor function a few constructor functions are built into the JavaScript language: the Date() function the Array() function the Object() function
50
Copyright (c) 2004 Prentice-Hall. All rights reserved. 50 Use Custom Objects and Properties (continued) Objects inherit the properties and methods of the class, or constructor function from which they are created When an object is created from a parent class we say the object is instantiated Custom objects are objects you can create in the code by creating a class and instantiating (creating) an object based on the class
51
Copyright (c) 2004 Prentice-Hall. All rights reserved. 51 Use Custom Objects and Properties (continued) Constructor functions consist of properties and methods A property of a custom object is a variable that exists within the constructor function A method of a custom object is a function that is called within the constructor function these methods can be methods that are built into JavaScript or other functions
52
Copyright (c) 2004 Prentice-Hall. All rights reserved. 52 Use Custom Objects and Properties (continued) The Object() method can be used to create an object: In the above example, the Object() function is the constructor method which creates a new object By using dot syntax, the other statements create properties for the person object person= new Object(); person.name="Joe" person.age=32; person.weight=160;
53
Copyright (c) 2004 Prentice-Hall. All rights reserved. 53 Use Custom Objects and Properties (continued) Basically, we have created an object and then created properties for the object The keyword this can be used to refer to the object that calls a function By using the this keyword, we can use a function to create a class
54
Copyright (c) 2004 Prentice-Hall. All rights reserved. 54 Use Custom Objects and Properties (continued) This constructor function is used to create a bank account object Example of creating a new object of this class: myAccount=newAccount("checking",500,10); function Account(type, minimum, fee) { // type means the type of account (such checking or savings) this.account_type=type; // minimum is the minimum balance this.account_minimum=mi nimum; // fee is the monthly fee this.account_fee=fee; }
55
Copyright (c) 2004 Prentice-Hall. All rights reserved. 55 Use Custom Objects and Properties (continued) JavaScript objects inherit all the variables and statements of the constructor function on which they are based This is known as inheritance The keyword this refers to the current object that called the constructor function
56
Copyright (c) 2004 Prentice-Hall. All rights reserved. 56 Use Custom Objects and Properties (continued) After creating a new object based on a constructor function, you can add additional properties to the object by using a period myAccount=new Account("checking",500,6); myAccount.balance="1000";
57
Copyright (c) 2004 Prentice-Hall. All rights reserved. 57 Use Custom Objects and Properties (continued) The prototype property is a built-in property that: specifies the constructor from which an object was created allows the property to extend to all objects created from the constructor The balance property can be created and added to the constructor function by using the following code: Account.prototype.balance=1500;
58
Copyright (c) 2004 Prentice-Hall. All rights reserved. 58 Use Custom Objects and Properties (continued) You can also create a new constructor function which is based on an existing function and adds additional properties Example of creating a CheckingAccount object which inherits the properties of the Account object Example of creating a CheckingAccount object which inherits the properties of the Account object
59
Copyright (c) 2004 Prentice-Hall. All rights reserved. 59 Use Custom Objects and Properties (continued) function CheckingAccount(classification, number) { // classification is type of account (personal or business) this.account_class=classification; // number is account number this.account_number=number; } CheckingAccount.prototype=new Account(); Example of creating a CheckingAccount object which inherits the properties of the Account object Example of creating a CheckingAccount object which inherits the properties of the Account object
60
Copyright (c) 2004 Prentice-Hall. All rights reserved. 60 Use Custom Objects and Properties (continued) A secondary type of object could be created for savings accounts function SavingsAccount(classification, number) { // classification is type of account (personal or business) this.account_class=classification; // number is account number this.account_number=number; } SavingsAccount.prototype=new Account();
61
Copyright (c) 2004 Prentice-Hall. All rights reserved. 61 Use Custom Objects and Properties (continued) Create a Custom Object You can use the Object() method to create a new object The Object() method: can be used with the keyword new for this purpose has limited usefulness since we cannot reuse the code to create additional similar objects
62
Copyright (c) 2004 Prentice-Hall. All rights reserved. 62 Use Custom Objects and Properties (continued) In JavaScript, all built in functions can be used as constructor functions by using the new keyword This is especially useful when working with: Dates Arrays Images where practical applications of the technology often require us to create these types of objects
63
Copyright (c) 2004 Prentice-Hall. All rights reserved. 63 Use Custom Objects and Properties (continued) object.html // create rectangle object var rectangle=new Object(); rectangle.height=12; rectangle.width=5; // use the object area=rectangle.height*rectangle.width; document.write("Area is "+area); Example of creating and using a custom object
64
Copyright (c) 2004 Prentice-Hall. All rights reserved. 64 Use Custom Objects and Properties (continued) Create an Object with a User Defined Function You can use the this keyword to create an object using a user defined function This allows multiple objects to be created from the same code Example Example
65
Copyright (c) 2004 Prentice-Hall. All rights reserved. 65 Use Custom Objects and Properties (continued) constructor.html function Vehicle(make,model) { this.vehicle_make=make; this.vehicle_model=model; } // end function // create an object from the constructor myCar=new Vehicle("Ford","Escort"); document.write(myCar.vehicle_make); document.write(" "); document.write(myCar.vehicle_model); Example of creating and using a custom object
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.