33
Topic 4 Topic 4 Objects Objects CMPS 211 CMPS 211 JavaScript JavaScript

Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

Embed Size (px)

Citation preview

Page 1: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

Topic 4Topic 4

ObjectsObjects

CMPS 211 CMPS 211 JavaScriptJavaScript

Page 2: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

2

Goals and ObjectivesGoals and Objectives GoalsGoals

Understand JavaScript objects, how to create and use your own Understand JavaScript objects, how to create and use your own objects, how to use JavaScript built-in objects, the impact of objects objects, how to use JavaScript built-in objects, the impact of objects on JavaScript syntax, and the use of objects with XHTML tagson JavaScript syntax, and the use of objects with XHTML tags

ObjectivesObjectives Importance of objects in web programmingImportance of objects in web programming DefinitionDefinition ConceptsConcepts ImplementationImplementation Nesting objectsNesting objects DOMDOM Associative arraysAssociative arrays Built-in objects: Built-in objects: document, Math, Date, Stringdocument, Math, Date, String

Page 3: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

3

Chapter HeadlinesChapter Headlines 1 1 IntroductionIntroduction

Is JavaScript and OO language? Why should it be?Is JavaScript and OO language? Why should it be? 2 2 DefinitionDefinition

Is car an object?Is car an object? 3 3 Creation and UseCreation and Use

Does JavaScript create and use a car as in real life?Does JavaScript create and use a car as in real life? 4 4 ConceptsConcepts

What is about objects?What is about objects? 5 5 Inheriting and Nesting ObjectsInheriting and Nesting Objects

Object family members save timeObject family members save time

Page 4: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

4

Chapter HeadlinesChapter Headlines 6 6 Document Object Modeling (DOM)Document Object Modeling (DOM)

Checkout this model before writing JavaScript codCheckout this model before writing JavaScript cod8 8 Document ObjectDocument Object

Find out what makes a web page in JavaScriptFind out what makes a web page in JavaScript 9 9 Math ObjectMath Object

And you thought JavaScript cannot do mathAnd you thought JavaScript cannot do math 10 10 Date ObjectDate Object

Create a real time date in a web pageCreate a real time date in a web page 11 11 String ObjectString Object

JavaScript makes text manipulation easyJavaScript makes text manipulation easy

Page 5: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

5

IntroductionIntroduction Object oriented programming (OOP) Object oriented programming (OOP) resembles real liferesembles real life OOP allows OOP allows code reuse, and modularitycode reuse, and modularity OO code is OO code is easy to followeasy to follow Objects have Objects have properties and behaviorsproperties and behaviors that that translatetranslate to to

variables and functionsvariables and functions in programs in programs JavaScript is JavaScript is based on OO paradigmbased on OO paradigm JavaScript is a JavaScript is a powerful OOP languagepowerful OOP language in the context of in the context of

web developmentweb development

Page 6: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

6

DefinitionDefinition Object is the Object is the basic unitbasic unit in OO code in OO code Objects have:Objects have:

AttributesAttributes they become variables in an OOP they become variables in an OOP BehaviorsBehaviors they become methods (functions) in an OOP they become methods (functions) in an OOP

JavaScript can create JavaScript can create user-defined objectsuser-defined objectsExamples: car, house, bank accounts, etc.Examples: car, house, bank accounts, etc.

JavaScript also provides it own JavaScript also provides it own predefined objectspredefined objectsExamples: Date, Math, String, etc.Examples: Date, Math, String, etc.

ObjectObject DefinitionDefinition MethodsMethodsBank accountBank account account numberaccount number depositdeposit

account owneraccount owner withdrawalwithdrawalaccount addressaccount addressaccount balanceaccount balance

Page 7: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

7

Creation and UseCreation and Use Object Object creation and use is essentialcreation and use is essential to realize all benefits to realize all benefits

of OOPof OOP OOP languages use OOP languages use three conceptsthree concepts to implement objects: to implement objects:

ClassesClasses InstantiationInstantiation Dot notationDot notation

Classes define objectsClasses define objects Instantiation creates themInstantiation creates them Dot notation uses themDot notation uses them

objectName.propertyName;objectName.propertyName; objectName.methodName();objectName.methodName();

JavaScript uses these conceptsJavaScript uses these concepts for object creation and use for object creation and use

Page 8: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

8

A House ObjectA House Object<?xml version="1.0" encoding="iso-8859-1"?> <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>A <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>A

House object</title> House object</title> <script language="javascript"> <script language="javascript"> //define House object //define House object function House (rms, stl, yr, garg) { function House (rms, stl, yr, garg) { this.rooms = rms; //attribute this.rooms = rms; //attribute this.style = stl; //attribute this.style = stl; //attribute this.yearBuilt = yr; //attribute this.yearBuilt = yr; //attribute this.hasGarage = garg; //attributethis.hasGarage = garg; //attribute }//House }//House //Create a house instance //Create a house instance myHouse = new House(5, "colonial", 1990, true); myHouse = new House(5, "colonial", 1990, true); //Use house instance //Use house instance document.write("My house has " + myHouse.rooms + " rooms<br />"); document.write("My house has " + myHouse.rooms + " rooms<br />"); document.write("My house style is " + myHouse.style + "<br />"); document.write("My house style is " + myHouse.style + "<br />"); document.write("My house was built in " + myHouse.yearBuilt +"<br />"); document.write("My house was built in " + myHouse.yearBuilt +"<br />"); document.write("My house has a garage: " + myHouse.hasGarage); document.write("My house has a garage: " + myHouse.hasGarage); </script></script></head> </head> <body> </body> </html><body> </body> </html>

Page 9: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

9

Creation and UseCreation and Use Classes Classes hold object definition, attributes, methods, hold object definition, attributes, methods,

constructorsconstructors Constructor FunctionConstructor Function

Special method to create and initialize instancesSpecial method to create and initialize instances InstantiationInstantiation

new new keyword is used to create an instance of an objectkeyword is used to create an instance of an object Dot notationDot notation

Allows an instance to access its class membersAllows an instance to access its class members The The thisthis reference reference

Powerful conceptPowerful concept and makes code efficient and elegant and makes code efficient and elegant Used to Used to reference class membersreference class members within constructor function within constructor function To reference the To reference the current objectcurrent object

Page 10: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

10

Create & UseCreate & Use<?xml version="1.0" encoding="iso-8859-<?xml version="1.0" encoding="iso-8859-

1"?> <!DOCTYPE html PUBLIC 1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xh"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> tml11.dtd">

<html <html xmlns="http://www.w3.org/1999/xhtml"xmlns="http://www.w3.org/1999/xhtml"> <head>> <head>

<meta http-equiv="Content-Type" <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-content="text/html; charset=iso-8859-1" /> 1" />

<title>A House object</title> <title>A House object</title> <script language="javascript"> <script language="javascript"> //define House object //define House object function House (rooms, style, yearBuilt, function House (rooms, style, yearBuilt,

hasGarage){ hasGarage){ this.rooms = rooms; //attribute this.rooms = rooms; //attribute this.style = style; //attribute this.style = style; //attribute this.yearBuilt = yearBuilt; //attributethis.yearBuilt = yearBuilt; //attributethis.hasGarage = hasGarage; //attributethis.hasGarage = hasGarage; //attribute

this.livingSpace = livingSpace; //behaviorthis.livingSpace = livingSpace; //behaviorthis.maintain = maintain; //behavior }this.maintain = maintain; //behavior }//House//House

//define livingSpace() function//define livingSpace() functionlivingSpace(length, width, numFloors){ livingSpace(length, width, numFloors){ return (length*width*numFloors); return (length*width*numFloors); } //livingSpace() } //livingSpace() //define maintain() function //define maintain() function maintain(){ maintain(){ return ("Keep the house in top shape"); return ("Keep the house in top shape"); } } //Create a house instance //Create a house instance myHouse = new House(5, "colonial", 1990, true); myHouse = new House(5, "colonial", 1990, true);

//Use house instance //Use house instance document.write("My house has " + document.write("My house has " +

myHouse.rooms + " rooms<br />"); myHouse.rooms + " rooms<br />"); document.write("My house style is " + document.write("My house style is " +

myHouse.style + "<br />"); myHouse.style + "<br />"); document.write("My house was built in " + document.write("My house was built in " +

myHouse.yearBuilt + "<br />");myHouse.yearBuilt + "<br />");document.write("My house has a garage: " + document.write("My house has a garage: " +

myHouse.hasGarage); myHouse.hasGarage); document.write("My house living space is: " + document.write("My house living space is: " +

myHouse.livingSpace(30, 70, 2) + " square myHouse.livingSpace(30, 70, 2) + " square feet<br />");feet<br />");

document.write(myHouse.maintain()); document.write(myHouse.maintain()); </script> </script> </head><body></body</head><body></body> </html> > </html>

Page 11: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

11

‘this’ Reference‘this’ Reference<?xml version="1.0" encoding="iso-8859-1"?> <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-<head> <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" /> 8859-1" /> <title>The this Reference</title> <title>The this Reference</title> <script language="javascript"> <script language="javascript"> //define Dog object //define Dog object function Dog (name, age){function Dog (name, age){ this.name = name; //attribute this.name = name; //attribute this.age = age; //attribute this.age = age; //attribute this.compareDogs = compareDogs; //behavior this.compareDogs = compareDogs; //behavior }//Dog }//Dog //define compare Dogs() function //define compare Dogs() function compareDogs(dog){ compareDogs(dog){ if (this.name == dog.name && this.age == dog.age) if (this.name == dog.name && this.age == dog.age) return true;return true; compareDogs() compareDogs()

Page 12: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

12

‘‘this’ Reference (cont)this’ Reference (cont)//Create four dog instances //Create four dog instances myDog = new Dog("Splinter", 4); myDog = new Dog("Splinter", 4); yourDog = new Dog("Spotter", 3);yourDog = new Dog("Spotter", 3); johnDog = new Dog("Spotter", 3); johnDog = new Dog("Spotter", 3); lisaDog = new Dog("Spotter", 5); lisaDog = new Dog("Spotter", 5); //these two dogs are not equal //these two dogs are not equal document.write("Comparing my dog and your dog produces: " + document.write("Comparing my dog and your dog produces: " +

myDog.compareDogs(yourDog) + "<br />");myDog.compareDogs(yourDog) + "<br />");document.write("====================================document.write("====================================

<br />"); //these two dogs are equal <br />"); //these two dogs are equal Document.write("Comparing your dog and John's dog produces: " + Document.write("Comparing your dog and John's dog produces: " +

yourDog.compareDogs(johnDog) + "<br />"); yourDog.compareDogs(johnDog) + "<br />"); document.write("====================================document.write("====================================

<br />"); <br />"); //these two dogs are not equal //these two dogs are not equal document.write("Comparing John's dog and Lisa's dog produces: " + document.write("Comparing John's dog and Lisa's dog produces: " +

johnDog.compareDogs(lisaDog)); johnDog.compareDogs(lisaDog)); </script></script> </head> <body> </body> </html> </head> <body> </body> </html>

Page 13: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

13

ConceptsConcepts OO conceptsOO concepts include include

AbstractionAbstraction ClassClass ConstructorsConstructors EncapsulationEncapsulation InstancesInstances InheritanceInheritance

Abstraction means Abstraction means thinking at higher levelthinking at higher level Abstraction Abstraction hides details of implementationhides details of implementation that may that may

not be relevant to an applicationnot be relevant to an application Data and functionalData and functional abstraction exist abstraction exist

Page 14: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

14

Inheriting and Nesting ObjectsInheriting and Nesting Objects Inheritance allows one object to Inheritance allows one object to inherit variables and inherit variables and

methodsmethods from another objects from another objects The class that we inherit from is The class that we inherit from is superclasssuperclass The class that inherits is The class that inherits is subclasssubclass Subclass can have Subclass can have additional methods and variablesadditional methods and variables Classes at the Classes at the bottom of the treebottom of the tree are are more specificmore specific JavaScript implements JavaScript implements inheritance through associationinheritance through association In association an In association an object is used in definitionobject is used in definition of another of another

object as an attributeobject as an attribute Objects are nested in Objects are nested in two different waystwo different ways

Passing objects as argumentsPassing objects as arguments to another’s constructor function to another’s constructor function Prototyping an objectPrototyping an object inside the another’s constructor function inside the another’s constructor function

Page 15: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

15

Inheriting and Nesting ObjectsInheriting and Nesting Objects

Page 16: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

16

Passing ObjectsPassing Objects<?xml version="1.0" encoding="iso-8859-1"?> <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Nesting Objects as Arguments</title> <title>Nesting Objects as Arguments</title> <script language="javascript"> <script language="javascript"> //define Employee object //define Employee object function Employee (name,department){ function Employee (name,department){ this.name = name; //attribute this.name = name; //attribute this.department = department; //attribute this.department = department; //attribute }//Employee }//Employee //define Manager object //define Manager object function Manager (staff, employee){ function Manager (staff, employee){ this.staff = staff; //attribute this.staff = staff; //attribute this.employee = employee; //nested object this.employee = employee; //nested object }//Manager }//Manager //Create eomplyee and manager instances //Create eomplyee and manager instances salesEmployee = new Employee ("Abe", "sales"); salesEmployee = new Employee ("Abe", "sales"); salesManager = new Manager(10, salesEmployee); salesManager = new Manager(10, salesEmployee); document.write ("Manager name is " + salesManager.employee.name + "<br />"); document.write ("Manager name is " + salesManager.employee.name + "<br />"); document.write ("Manager department is " + salesManager.employee.department + "<br />"); document.write ("Manager department is " + salesManager.employee.department + "<br />"); document.write ("Manager " + salesManager.employee.name + " manages " + salesManager.staff + " document.write ("Manager " + salesManager.employee.name + " manages " + salesManager.staff + "

people"); people"); </script> </script> </head> <body> </body> </html> </head> <body> </body> </html>

Page 17: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

17

Prototyping ObjectsPrototyping Objects<?xml version="1.0" encoding="iso-8859-1"?> <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="author" content="zeid" /> <meta name="generator" <meta name="author" content="zeid" /> <meta name="generator" content="AceHTML 5 Freeware" /> content="AceHTML 5 Freeware" /> <!-- Compare the code of this example with the code of Slide 16 to understand the difference between nesting <!-- Compare the code of this example with the code of Slide 16 to understand the difference between nesting

objects via arguments or via prototyping --> objects via arguments or via prototyping --> <title>Nesting Objects by Prototyping</title> <title>Nesting Objects by Prototyping</title> <script language="javascript"> <script language="javascript"> //define Employee object //define Employee object function Employee (name,department){ function Employee (name,department){ this.name = name; //attribute this.name = name; //attribute this.department = department; //attribute this.department = department; //attribute }//Employee }//Employee //define Manager object //define Manager object function Manager (staff){ function Manager (staff){ this.staff = staff; //attribute this.staff = staff; //attribute Manager.prototype = new Employee; //nested object Manager.prototype = new Employee; //nested object }//Manager }//Manager //Create a manager instance //Create a manager instance salesManager = new Manager(10); salesManager = new Manager(10); //assign attribute (property) values to manager instance //assign attribute (property) values to manager instance salesManager.name="Abe"; salesManager.name="Abe"; salesManager.department = "sales"; salesManager.department = "sales"; document.write ("Manager name is " + salesManager.name + "<br />"); document.write ("Manager department document.write ("Manager name is " + salesManager.name + "<br />"); document.write ("Manager department

is " + salesManager.department + "<br />"); is " + salesManager.department + "<br />"); document.write ("Manager " + salesManager.name + " manages " + salesManager.staff + " people"); document.write ("Manager " + salesManager.name + " manages " + salesManager.staff + " people"); </script> </script> </head> <body> </body> </html> </head> <body> </body> </html>

Page 18: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

18

Document Object Model (DOM)Document Object Model (DOM) DOM convertsDOM converts XHTML elements of the web page into XHTML elements of the web page into

JavaScript built-in objectsJavaScript built-in objects Each objects has Each objects has predefined variables and methodspredefined variables and methods that that

become available to JavaScript codebecome available to JavaScript code Every web page has the following objects:Every web page has the following objects:

NavigatorNavigator properties for name and version of the browser properties for name and version of the browser Window Window for the browser window and every frame of a set for the browser window and every frame of a set Document Document refers to the web page currently displayed refers to the web page currently displayed Location Location contains the web page URL contains the web page URL History History has the previously requested URLs has the previously requested URLs

We must use the We must use the dot notation chain to accessdot notation chain to access object object propertiesproperties

Page 19: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

19

Document Object Model (DOM)Document Object Model (DOM)

Page 20: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

20

Objects and ArraysObjects and Arrays The list of properties of an The list of properties of an object lends itself to arrayobject lends itself to array

representationrepresentation JavaScript JavaScript associates an array to objectassociates an array to object properties and properties and

such an array is called such an array is called associative arrayassociative array We can We can access the elementsaccess the elements of such an array using the of such an array using the

number or string for the array element indexnumber or string for the array element indexExample: Example: myCar[1], myCar[“model”]myCar[1], myCar[“model”]

Some Some predefined JavaScript arrayspredefined JavaScript arrays and their poperties: and their poperties: Navigator Navigator mimeTypes, plugins mimeTypes, plugins Window Window history, frames history, frames Document Document links, anchors, images, forms, applets, embeds links, anchors, images, forms, applets, embeds Form Form elements elements Select Select options options

Page 21: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

21

Associative ArraysAssociative Arrays<?xml version="1.0" encoding="iso-8859-1"?> <?xml version="1.0" encoding="iso-8859-1"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-<head> <meta http-equiv="Content-Type" content="text/html; charset=iso-

8859-1" /> 8859-1" /> <title>Nesting Objects as Arguments</title> <title>Nesting Objects as Arguments</title> <script language="javascript"> <script language="javascript"> //define Employee object //define Employee object function Employee (name,department){ function Employee (name,department){ this.name = name; //attribute this.name = name; //attribute this.department = department; //attribute this.department = department; //attribute }//Employee }//Employee //define Manager object //define Manager object function Manager (staff, employee){function Manager (staff, employee){ this.staff = staff; //attribute this.staff = staff; //attribute this.employee = employee; //nested object this.employee = employee; //nested object }//Manager }//Manager //Use associative array to print any object properties //Use associative array to print any object properties

Page 22: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

22

Associative Arrays (Cont)Associative Arrays (Cont)function print(obj, objName){ function print(obj, objName){ props = ""; props = ""; for (i in obj){for (i in obj){ if (obj[i] instanceof Object){ if (obj[i] instanceof Object){ for (j in obj[i]) props += objName + "." + j + " = " + obj[i][j] + "<br />"; } //if else for (j in obj[i]) props += objName + "." + j + " = " + obj[i][j] + "<br />"; } //if else

props += objName + "." + i + " = " + obj[i] + "<br />"; } //for return props; } props += objName + "." + i + " = " + obj[i] + "<br />"; } //for return props; } //print() //print()

//Create eomplyee and manager instances //Create eomplyee and manager instances salesEmployee = new Employee ("Abe", "sales"); salesEmployee = new Employee ("Abe", "sales"); salesManager = new Manager(10, salesEmployee); salesManager = new Manager(10, salesEmployee); document.write("Printing object proeperites using strings as indexes for the associative document.write("Printing object proeperites using strings as indexes for the associative

array elements<br />"); document.write ("Manager " + array elements<br />"); document.write ("Manager " + salesManager.employee['name'] + " manages " + salesManager['staff'] + " people<br salesManager.employee['name'] + " manages " + salesManager['staff'] + " people<br />"); />");

document.write ("Manager name is " + salesManager.employee['name'] + "<br />"); document.write ("Manager name is " + salesManager.employee['name'] + "<br />"); document.write ("Manager department is " + document.write ("Manager department is " + salesManager.employee['department'] + "<br />"); salesManager.employee['department'] + "<br />"); document.write("<br />===========================<br />"); document.write("<br />===========================<br />"); //print slaesmanager another way //print slaesmanager another way document.write("Printing object proeperites using numbers as indexes for the associative document.write("Printing object proeperites using numbers as indexes for the associative

array elements<br />"); array elements<br />"); document.write(print(salesManager, "salesmanager")); document.write(print(salesManager, "salesmanager")); </script> </head> <body> </body> </html> </script> </head> <body> </body> </html>

Page 23: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

23

Document ObjectDocument Object document document is a is a popular JavaScript objectpopular JavaScript object Variables of this object:Variables of this object:alinkcolor, anchors[], applets[], bgcolor, alinkcolor, anchors[], applets[], bgcolor, cookie, domain, embeds[], fgcolor, forms[], cookie, domain, embeds[], fgcolor, forms[], images[], lastModified, linkColor, links[], images[], lastModified, linkColor, links[], location, plugins, referrer, title, URL, location, plugins, referrer, title, URL, vlinkColorvlinkColor

Methods of this object:Methods of this object:clear(), close(), open(), write(), writeln()clear(), close(), open(), write(), writeln()

Page 24: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

24

Math ObjectMath Object Math Math object class object class cannot be instantiatedcannot be instantiated and all its and all its

constants, variables and methods are constants, variables and methods are staticstatic Thus, Thus, dot notation must use the class namedot notation must use the class name Constants:Constants:Math.PI, Math.SQRT1_2, Math.SQRT2, Math.E, Math.PI, Math.SQRT1_2, Math.SQRT2, Math.E, Math.LN10, Math.LN2, Math.LOG10E, Math.LOG2EMath.LN10, Math.LN2, Math.LOG10E, Math.LOG2E

Variables:Variables:NONENONE

Methods:Methods:abs(), acos(), asin(), atan(), atan2(), abs(), acos(), asin(), atan(), atan2(), ceil(), cos(), exp(), floor(), log(), max(), ceil(), cos(), exp(), floor(), log(), max(), min(), pow(), random(), round(), sin(), min(), pow(), random(), round(), sin(), sqrt(), tan()sqrt(), tan()

Page 25: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

25

Math ObjectMath Object<?xml version="1.0" encoding="iso-8859-1"?> <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Nesting Objects as Arguments</title> <title>Nesting Objects as Arguments</title> <script language="javascript"> <script language="javascript"> //use methods of the Math object object //use methods of the Math object object document.write("Math.abs(-25) = " + Math.abs(-25) + "<br />");document.write("Math.abs(-25) = " + Math.abs(-25) + "<br />"); document.write("Math.acos(.5) = " + Math.acos(0.5) + " radians<br />"); document.write("Math.acos(.5) = " + Math.acos(0.5) + " radians<br />"); document.write("Math.asin(.5) = " + Math.asin(0.5) + " radians<br />"); document.write("Math.asin(.5) = " + Math.asin(0.5) + " radians<br />"); document.write("Math.atan(1) = " + Math.atan(1) + " radians<br />"); document.write("Math.atan(1) = " + Math.atan(1) + " radians<br />"); document.write("Math.atan2(1,math.sqrt(3)) = " + Math.atan2(1,Math.sqrt(3)) + " radians<br document.write("Math.atan2(1,math.sqrt(3)) = " + Math.atan2(1,Math.sqrt(3)) + " radians<br

/>"); />"); document.write("Math.ceil(3.4) = " + Math.ceil(3.4) + "<br />"); document.write("Math.ceil(3.4) = " + Math.ceil(3.4) + "<br />"); document.write("Math.cos(1.04719755119659) = " + Math.cos(1.04719755119659) + "<br />"); document.write("Math.cos(1.04719755119659) = " + Math.cos(1.04719755119659) + "<br />"); document.write("Math.exp(2) = " + Math.exp(2) + "<br />"); document.write("Math.exp(2) = " + Math.exp(2) + "<br />"); document.write("Math.floor(3.7) = " + Math.floor(3.7) + "<br />"); document.write("Math.floor(3.7) = " + Math.floor(3.7) + "<br />"); document.write("Math.log(4.5) = " + Math.log(4.5) + "<br />"); document.write("Math.log(4.5) = " + Math.log(4.5) + "<br />"); document.write("Math.max(3.5, -9) = " + Math.max(3.5,-9) + "<br />"); document.write("Math.max(3.5, -9) = " + Math.max(3.5,-9) + "<br />"); document.write("Math.min(3.5, -9) = " + Math.min(3.5, -9) + "<br />"); document.write("Math.min(3.5, -9) = " + Math.min(3.5, -9) + "<br />"); document.write("Math.pow(2, 3) = " + Math.pow(2, 3) + "<br />"); document.write("Math.pow(2, 3) = " + Math.pow(2, 3) + "<br />"); document.write("Math.random() = " + Math.random() + "<br />"); document.write("Math.random() = " + Math.random() + "<br />"); document.write("Math.round(3.1) = " + Math.round(3.1) + "<br />"); document.write("Math.round(3.1) = " + Math.round(3.1) + "<br />"); document.write("Math.round(3.6) = " + Math.round(3.6) + "<br />"); document.write("Math.round(3.6) = " + Math.round(3.6) + "<br />"); document.write("Math.sin(0.5235987755982989 ) = " + Math.sin(0.5235987755982989 ) + document.write("Math.sin(0.5235987755982989 ) = " + Math.sin(0.5235987755982989 ) +

"<br />"); "<br />"); document.write("Math.sqrt(4) = " + Math.sqrt(4) + "<br />"); document.write("Math.sqrt(4) = " + Math.sqrt(4) + "<br />");

document.write("Math.tan(0.7853981633974483 ) = " + Math.tan(0.7853981633974483 ) + document.write("Math.tan(0.7853981633974483 ) = " + Math.tan(0.7853981633974483 ) + "<br />"); </script> </head> <body> </body> </html> "<br />"); </script> </head> <body> </body> </html>

Page 26: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

26

Date ObjectDate Object Date Date object can object can display the current datedisplay the current date in a web page in a web page It has It has multiple constructorsmultiple constructors Constructors:Constructors:Date(), Date(milliseconds), Date(string), Date(), Date(milliseconds), Date(string), Date(year, month, day, hours, minutes, Date(year, month, day, hours, minutes, seconds, milliseconds)seconds, milliseconds)

Variables:Variables:NONENONE

Methods:Methods:Bunch of Bunch of setset and and getget methods to methods to assign values to the assign values to the parametersparameters of of DateDate instance instance

Page 27: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

27

Date ObjectDate Object<?xml version="1.0" encoding="iso-8859-1"?> <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type“<head> <meta http-equiv="Content-Type“ontent="text/html; charset=iso-8859-1" /> ontent="text/html; charset=iso-8859-1" /> <title>Date Formatting in JavaScript</title> <title>Date Formatting in JavaScript</title> <script language="javascript"> <script language="javascript"> //use methods of the Date object //use methods of the Date object <!-- Hide from ancient Browsers <!-- Hide from ancient Browsers // Global Day Names and Month Names for Date Formatting Routines // Global Day Names and Month Names for Date Formatting Routines dayArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", dayArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",

"Saturday"); "Saturday"); monthArray = new Array("January", "February", "March", "April", "May", "June", "July", "August", monthArray = new Array("January", "February", "March", "April", "May", "June", "July", "August",

"September", "October", "November", "December"); "September", "October", "November", "December"); // Function returns a string of the passed in Date formatted as: // Function returns a string of the passed in Date formatted as: // DayOfWeek MonthName Day, FourDigitYear // DayOfWeek MonthName Day, FourDigitYear // e.g. Thursday Novemebr 13, 2003 // e.g. Thursday Novemebr 13, 2003 function displayDate(inDate) function displayDate(inDate) {{ str = dayArray[inDate.getDay()]; str = dayArray[inDate.getDay()]; str += " " + monthArray[inDate.getMonth()]; str += " " + monthArray[inDate.getMonth()]; str += " " + inDate.getDate(); str += " " + inDate.getDate(); // Browsers return different values for Date.getYear() // Browsers return different values for Date.getYear() // (Netscape 4.x) always show 2 digit years // (Netscape 4.x) always show 2 digit years // (IE and Netscape 3.x) show 4 digits in 2000 and beyond // (IE and Netscape 3.x) show 4 digits in 2000 and beyond // formula good to the year 2899 although other limts occur well before then! // formula good to the year 2899 although other limts occur well before then! theYear = inDate.getYear(); theYear = inDate.getYear(); str += ", " + (theYear + (theYear < 1000 ? 1900 : 0)); str += ", " + (theYear + (theYear < 1000 ? 1900 : 0)); return str; return str; }}

Page 28: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

28

Date Object (Cont)Date Object (Cont)d = new Date(); d = new Date(); document.write("<BR>Date Value = " + d); document.write("<BR>Date Value = " + d); document.write("<BR>Date.getYear() = " + d.getYear()); document.write("<BR>Date.getYear() = " + d.getYear()); document.write("<BR><B>Today = " + displayDate(d) +"</B>"); document.write("<BR><B>Today = " + displayDate(d) +"</B>"); document.write("<BR>*********************************<BR>");document.write("<BR>*********************************<BR>"); // Show the difference between a 19xx year and 20xx year// Show the difference between a 19xx year and 20xx year moonDate = new Date(1969, 6, 20); document.write("<BR>Man walked on moonDate = new Date(1969, 6, 20); document.write("<BR>Man walked on

the moon on: " + displayDate(moonDate)); document.write("<BR>The the moon on: " + displayDate(moonDate)); document.write("<BR>The year was " + moonDate.getYear()); year was " + moonDate.getYear());

document.write("<BR>*********************************<BR>"); wtcDate = document.write("<BR>*********************************<BR>"); wtcDate = new Date(2001, 8, 11); new Date(2001, 8, 11);

document.write("<BR>The world will remember " + displayDate(wtcDate)); document.write("<BR>The world will remember " + displayDate(wtcDate)); document.write("<BR>The year was " + wtcDate.getYear()); document.write("<BR>The year was " + wtcDate.getYear()); document.close(); // End Browser Hiding --> document.close(); // End Browser Hiding --> </script> </script> </head> </head> <body> <body> </body> </body> </html> </html>

Page 29: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

29

String ObjectString Object String String object has methods that allow us to object has methods that allow us to control the control the

appearance of stringappearance of string, and , and manipulate themmanipulate them StringString object has object has only one propertyonly one property for number of for number of

characterscharacters Variables:Variables:lengthlength

Methods:Methods:anchor(), blink(), bold(), charAt(), anchor(), blink(), bold(), charAt(), concat(), fixed(), fontcolor(), fontsize(), concat(), fixed(), fontcolor(), fontsize(), italics(), link(), match(), replace(), italics(), link(), match(), replace(), search(), slice(), split(), strike(), sub(), search(), slice(), split(), strike(), sub(), substr(), sup(), toLowerCase(), toUpperCase()substr(), sup(), toLowerCase(), toUpperCase()

Page 30: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

30

String ObjectString Object<?xml version="1.0" encoding="iso-8859-1"?><?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Using String methods</title> <title>Using String methods</title> <script language="javascript"> <script language="javascript"> //define a string //define a string str = "This is how the world ends!"; str = "This is how the world ends!"; document.write("We apply the String methods to this text:"); document.write("We apply the String methods to this text:"); document.write("<h2>str = " + str + "</h2>"); document.write("<h2>str = " + str + "</h2>"); document.write("================================"); document.write("================================"); //use the only variable of the String object //use the only variable of the String object document.write("<br />str.length = " + str.length); document.write("<br />str.length = " + str.length); //use the methods of the String object //use the methods of the String object document.write("<br />str.anchor('name') ==> " + str.anchor("name")); document.write("<br />str.anchor('name') ==> " + str.anchor("name")); document.write("<br />str.big() ==> " + str.big()); document.write("<br />str.big() ==> " + str.big()); document.write("<br />str.bold() ==> " + str.bold()); document.write("<br />str.bold() ==> " + str.bold()); document.write("<br />str.charAt(3) ==> " + str.charAt(3)); document.write("<br />str.charAt(3) ==> " + str.charAt(3)); document.write("<br />str.charCodeAt(3) ==> " + str.charCodeAt(3)); document.write("<br />str.charCodeAt(3) ==> " + str.charCodeAt(3)); document.write("<br />str.concat('OK') ==> " + str.concat(" OK")); document.write("<br />str.concat('OK') ==> " + str.concat(" OK")); document.write("<br />str.fixed() ==> " + str.fixed()); document.write("<br />str.fixed() ==> " + str.fixed()); document.write("<br />str.fontcolor('#FF0000') ==> " + str.fontcolor("#FF0000")); document.write("<br />str.fontcolor('#FF0000') ==> " + str.fontcolor("#FF0000")); document.write("<br />str.fontsize(3) ==> " + str.fontsize(5)); document.write("<br />str.fontsize(3) ==> " + str.fontsize(5));

Page 31: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

31

String Object (Cont)String Object (Cont)document.write("<br />str.indexOf('s') ==> " + str.indexOf('s')); document.write("<br />str.indexOf('s') ==> " + str.indexOf('s')); document.write("<br />str.italics() ==> " + str.italics()); document.write("<br />str.italics() ==> " + str.italics()); document.write("<br />str.lastIndexOf('s') ==> " + str.lastIndexOf('s')); document.write("<br />str.lastIndexOf('s') ==> " + str.lastIndexOf('s')); document.write("<br />str.link() ==> " + str.link()); document.write("<br />str.link() ==> " + str.link()); document.write("<br />str.match('k') ==> " + str.match("k")); document.write("<br />str.match('k') ==> " + str.match("k")); document.write("<br />str.replace('s', 'k') ==> " + str.replace("s", "k")); document.write("<br />str.replace('s', 'k') ==> " + str.replace("s", "k")); document.write("<br />str.search('s') ==> " + str.search("s")); document.write("<br />str.search('s') ==> " + str.search("s")); document.write("<br />str.slice(7, 11) ==> " + str.slice(7,11)); document.write("<br />str.slice(7, 11) ==> " + str.slice(7,11)); document.write("<br />str.small() ==> " + str.small()); document.write("<br />str.small() ==> " + str.small()); document.write("<br />str.split(' ') ==> " + str.split(" ")); words = str.split(" "); document.write("<br />str.split(' ') ==> " + str.split(" ")); words = str.split(" "); for (i=0; i<words.length; i++){ for (i=0; i<words.length; i++){ document.write("<br />" + words[i]); document.write("<br />" + words[i]); } //for } //for document.write("<br />str.strike() ==> " + str.strike()); document.write("<br />str.strike() ==> " + str.strike()); document.write("<br />str.sub() ==> " + str.sub()); document.write("<br />str.sub() ==> " + str.sub()); document.write("<br />str.substring(7, 11) ==> " + str.substring(7, 11)); document.write("<br />str.substring(7, 11) ==> " + str.substring(7, 11)); document.write("<br />str.substr(7, 4) ==> " + str.substr(7, 4)); document.write("<br />str.substr(7, 4) ==> " + str.substr(7, 4)); document.write("<br />str.sup() ==> " + str.sup()); document.write("<br />str.sup() ==> " + str.sup()); document.write("<br />str.toLowercase() ==> " + str.toLowerCase()); document.write("<br />str.toLowercase() ==> " + str.toLowerCase()); document.write("<br />str.toUpperCase() ==> " + str.toUpperCase()); document.write("<br />str.toUpperCase() ==> " + str.toUpperCase()); </script> </head> <body> </body> </html> </script> </head> <body> </body> </html>

Page 32: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

32

Random colorsRandom colors<?xml version="1.0" encoding="iso-8859-1"?> <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" “<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" “<!-- Generated by AceHTM http://freeware.acehtml.com --> <!-- Generated by AceHTM http://freeware.acehtml.com --> <head> <meta http-equiv="Content-Type" content="text/html; <head> <meta http-equiv="Content-Type" content="text/html;

charset=iso-8859-1" /> charset=iso-8859-1" /> <title>Random Color Generator</title> <title>Random Color Generator</title> <script language="javascript"> <script language="javascript"> //generate a random hex color //generate a random hex color color = "#" + Math.floor(Math.random()*100) + color = "#" + Math.floor(Math.random()*100) +

Math.floor(Math.random()*100) + Math.floor(Math.random()*100) + Math.floor(Math.random()*100); Math.floor(Math.random()*100);

//display color hex code //display color hex code alert (color); alert (color); //apply random color to text //apply random color to text str = "<h1>This is randomly colored text</font></h1>"; str = "<h1>This is randomly colored text</font></h1>"; document.write(str.fontcolor(color)); </script> document.write(str.fontcolor(color)); </script> </head> <body></body></html> </head> <body></body></html>

Page 33: Topic 4 Objects CMPS 211 JavaScript. 2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to

33

SummarySummary• Objects impart Objects impart code reuse and modularitycode reuse and modularity• Objects has Objects has attributes and behaviorsattributes and behaviors• Objects have to be Objects have to be created and used created and used in a certain mannerin a certain manner• AbstractionAbstraction hides the details from the application hides the details from the application• Objects can be Objects can be inherited and nestedinherited and nested• DOM convertsDOM converts XHTML elements into JavaScript objects XHTML elements into JavaScript objects• JavaScript JavaScript associates an array to object associates an array to object propertiesproperties• documentdocument object has object has variables and methodsvariables and methods• Math Math object provides object provides math functions and constantsmath functions and constants• Date Date object object display the current datedisplay the current date in a web page in a web page• String String object allows object allows text manipulationstext manipulations