Download presentation
Presentation is loading. Please wait.
Published byDora Hicks Modified over 9 years ago
1
Topic 4 Objects CMPS 211 JavaScript
2
2 Goals and Objectives Goals Goals Understand JavaScript objects, how to create and use your own objects, how to use JavaScript built-in objects, the impact of objects on JavaScript syntax, and the use of objects with XHTML tags Objectives Objectives Importance of objects in web programming Importance of objects in web programming Definition Definition Concepts Concepts Implementation Implementation Nesting objects Nesting objects DOM DOM Associative arrays Associative arrays Built-in objects: document, Math, Date, String Built-in objects: document, Math, Date, String
3
3 Chapter Headlines 1 Introduction 1 Introduction Is JavaScript and OO language? Why should it be? Is JavaScript and OO language? Why should it be? 2 Definition 2 Definition Is car an object? Is car an object? 3 Creation and Use 3 Creation 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 Concepts 4 Concepts What is about objects? What is about objects? 5 Inheriting and Nesting Objects 5 Inheriting and Nesting Objects Object family members save time Object family members save time
4
4 Chapter Headlines 6 Document Object Modeling (DOM) 6 Document Object Modeling (DOM) Checkout this model before writing JavaScript cod 8 Document Object Checkout this model before writing JavaScript cod 8 Document Object Find out what makes a web page in JavaScript Find out what makes a web page in JavaScript 9 Math Object 9 Math Object And you thought JavaScript cannot do math And you thought JavaScript cannot do math 10 Date Object 10 Date Object Create a real time date in a web page Create a real time date in a web page 11 String Object 11 String Object JavaScript makes text manipulation easy JavaScript makes text manipulation easy
5
5Introduction Object oriented programming (OOP) resembles real life Object oriented programming (OOP) resembles real life OOP allows code reuse, and modularity OOP allows code reuse, and modularity OO code is easy to follow OO code is easy to follow Objects have properties and behaviors that translate to variables and functions in programs Objects have properties and behaviors that translate to variables and functions in programs JavaScript is based on OO paradigm JavaScript is based on OO paradigm JavaScript is a powerful OOP language in the context of web development JavaScript is a powerful OOP language in the context of web development
6
6Definition Object is the basic unit in OO code Object is the basic unit in OO code Objects have: Objects have: Attributes they become variables in an OOP Attributes they become variables in an OOP Behaviors they become methods (functions) in an OOP Behaviors they become methods (functions) in an OOP JavaScript can create user-defined objects Examples: car, house, bank accounts, etc. JavaScript can create user-defined objects Examples: car, house, bank accounts, etc. JavaScript also provides it own predefined objects Examples: Date, Math, String, etc. JavaScript also provides it own predefined objects Examples: Date, Math, String, etc. ObjectDefinitionMethods Bank accountaccount numberdeposit account ownerwithdrawal account address account balance
7
7 Creation and Use Object creation and use is essential to realize all benefits of OOP Object creation and use is essential to realize all benefits of OOP OOP languages use three concepts to implement objects: OOP languages use three concepts to implement objects: Classes Classes Instantiation Instantiation Dot notation Dot notation Classes define objects Classes define objects Instantiation creates them Instantiation creates them Dot notation uses them Dot notation uses them objectName.propertyName; objectName.propertyName; objectName.methodName(); objectName.methodName(); JavaScript uses these concepts for object creation and use JavaScript uses these concepts for object creation and use
8
8 A House Object A House Object <head> A House object A House object //define House object 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; //attribute this.hasGarage = garg; //attribute }//House }//House //Create a house instance myHouse = new House(5, "colonial", 1990, true); //Use house instance document.write("My house has " + myHouse.rooms + " rooms "); document.write("My house style is " + myHouse.style + " "); document.write("My house was built in " + myHouse.yearBuilt +" "); document.write("My house has a garage: " + myHouse.hasGarage); </script></head>
9
9 Creation and Use Classes hold object definition, attributes, methods, constructors Classes hold object definition, attributes, methods, constructors Constructor Function Constructor Function Special method to create and initialize instances Special method to create and initialize instances Instantiation Instantiation new keyword is used to create an instance of an object new keyword is used to create an instance of an object Dot notation Dot notation Allows an instance to access its class members Allows an instance to access its class members The this reference The this reference Powerful concept and makes code efficient and elegant Powerful concept and makes code efficient and elegant Used to reference class members within constructor function Used to reference class members within constructor function To reference the current object To reference the current object
10
10 Create & Use Create & Use A House object A House object //define House object function House (rooms, style, yearBuilt, hasGarage){ this.rooms = rooms; //attribute this.style = style; //attribute this.yearBuilt = yearBuilt; //attribute this.hasGarage = hasGarage; //attribute this.livingSpace = livingSpace; //behavior this.maintain = maintain; //behavior } //House //define livingSpace() function livingSpace(length, width, numFloors){ return (length*width*numFloors); } //livingSpace() //define maintain() function maintain(){ return ("Keep the house in top shape"); } //Create a house instance myHouse = new House(5, "colonial", 1990, true); //Use house instance document.write("My house has " + myHouse.rooms + " rooms "); document.write("My house style is " + myHouse.style + " "); document.write("My house was built in " + myHouse.yearBuilt + " "); document.write("My house has a garage: " + myHouse.hasGarage); document.write("My house living space is: " + myHouse.livingSpace(30, 70, 2) + " square feet "); document.write(myHouse.maintain());
11
11 ‘this’ Reference ‘this’ Reference The this Reference The this Reference //define Dog object function Dog (name, age){ this.name = name; //attribute this.name = name; //attribute this.age = age; //attribute this.compareDogs = compareDogs; //behavior }//Dog //define compare Dogs() function compareDogs(dog){ if (this.name == dog.name && this.age == dog.age) return true; return true; compareDogs() compareDogs()
12
12 ‘this’ Reference (cont) //Create four dog instances myDog = new Dog("Splinter", 4); yourDog = new Dog("Spotter", 3); johnDog = new Dog("Spotter", 3); johnDog = new Dog("Spotter", 3); lisaDog = new Dog("Spotter", 5); //these two dogs are not equal document.write("Comparing my dog and your dog produces: " + myDog.compareDogs(yourDog) + " "); document.write("==================================== "); //these two dogs are equal Document.write("Comparing your dog and John's dog produces: " + yourDog.compareDogs(johnDog) + " "); document.write("==================================== "); //these two dogs are not equal document.write("Comparing John's dog and Lisa's dog produces: " + johnDog.compareDogs(lisaDog)); </script>
13
13Concepts OO concepts include OO concepts include Abstraction Abstraction Class Class Constructors Constructors Encapsulation Encapsulation Instances Instances Inheritance Inheritance Abstraction means thinking at higher level Abstraction means thinking at higher level Abstraction hides details of implementation that may not be relevant to an application Abstraction hides details of implementation that may not be relevant to an application Data and functional abstraction exist Data and functional abstraction exist
14
14 Inheriting and Nesting Objects Inheritance allows one object to inherit variables and methods from another objects Inheritance allows one object to inherit variables and methods from another objects The class that we inherit from is superclass The class that we inherit from is superclass The class that inherits is subclass The class that inherits is subclass Subclass can have additional methods and variables Subclass can have additional methods and variables Classes at the bottom of the tree are more specific Classes at the bottom of the tree are more specific JavaScript implements inheritance through association JavaScript implements inheritance through association In association an object is used in definition of another object as an attribute In association an object is used in definition of another object as an attribute Objects are nested in two different ways Objects are nested in two different ways Passing objects as arguments to another’s constructor function Passing objects as arguments to another’s constructor function Prototyping an object inside the another’s constructor function Prototyping an object inside the another’s constructor function
15
15 Inheriting and Nesting Objects
16
16 Passing Objects Passing Objects <head> Nesting Objects as Arguments Nesting Objects as Arguments //define Employee object function Employee (name,department){ this.name = name; //attribute this.department = department; //attribute }//Employee //define Manager object function Manager (staff, employee){ this.staff = staff; //attribute this.employee = employee; //nested object }//Manager //Create eomplyee and manager instances salesEmployee = new Employee ("Abe", "sales"); salesManager = new Manager(10, salesEmployee); document.write ("Manager name is " + salesManager.employee.name + " "); document.write ("Manager department is " + salesManager.employee.department + " "); document.write ("Manager " + salesManager.employee.name + " manages " + salesManager.staff + " people"); </script>
17
17 Prototyping Objects Prototyping Objects <meta name="generator" content="AceHTML 5 Freeware" /> Nesting Objects by Prototyping Nesting Objects by Prototyping //define Employee object function Employee (name,department){ this.name = name; //attribute this.department = department; //attribute }//Employee //define Manager object function Manager (staff){ this.staff = staff; //attribute Manager.prototype = new Employee; //nested object }//Manager //Create a manager instance salesManager = new Manager(10); //assign attribute (property) values to manager instance salesManager.name="Abe"; salesManager.department = "sales"; document.write ("Manager name is " + salesManager.name + " "); document.write ("Manager department is " + salesManager.department + " "); document.write ("Manager " + salesManager.name + " manages " + salesManager.staff + " people"); </script>
18
18 Document Object Model (DOM) DOM converts XHTML elements of the web page into JavaScript built-in objects DOM converts XHTML elements of the web page into JavaScript built-in objects Each objects has predefined variables and methods that become available to JavaScript code Each objects has predefined variables and methods that become available to JavaScript code Every web page has the following objects: Every web page has the following objects: Navigator properties for name and version of the browser Navigator properties for name and version of the browser Window for the browser window and every frame of a set Window for the browser window and every frame of a set Document refers to the web page currently displayed Document refers to the web page currently displayed Location contains the web page URL Location contains the web page URL History has the previously requested URLs History has the previously requested URLs We must use the dot notation chain to access object properties We must use the dot notation chain to access object properties
19
19 Document Object Model (DOM)
20
20 Objects and Arrays The list of properties of an object lends itself to array representation JavaScript associates an array to object properties and such an array is called associative array We can access the elements of such an array using the number or string for the array element index Example: myCar[1], myCar[“model”] Some predefined JavaScript arrays and their poperties: Navigator mimeTypes, plugins Window history, frames Document links, anchors, images, forms, applets, embeds Form elements Select options
21
21 Associative Arrays Associative Arrays Nesting Objects as Arguments Nesting Objects as Arguments //define Employee object function Employee (name,department){ this.name = name; //attribute this.department = department; //attribute }//Employee //define Manager object function Manager (staff, employee){ this.staff = staff; //attribute this.staff = staff; //attribute this.employee = employee; //nested object }//Manager //Use associative array to print any object properties
22
22 Associative Arrays (Cont) function print(obj, objName){ 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] + " "; } //if else props += objName + "." + i + " = " + obj[i] + " "; } //for return props; } //print() for (j in obj[i]) props += objName + "." + j + " = " + obj[i][j] + " "; } //if else props += objName + "." + i + " = " + obj[i] + " "; } //for return props; } //print() //Create eomplyee and manager instances salesEmployee = new Employee ("Abe", "sales"); salesManager = new Manager(10, salesEmployee); document.write("Printing object proeperites using strings as indexes for the associative array elements "); document.write ("Manager " + salesManager.employee['name'] + " manages " + salesManager['staff'] + " people "); document.write ("Manager name is " + salesManager.employee['name'] + " "); document.write ("Manager department is " + salesManager.employee['department'] + " "); document.write(" =========================== "); //print slaesmanager another way document.write("Printing object proeperites using numbers as indexes for the associative array elements "); document.write(print(salesManager, "salesmanager"));
23
23 Document Object document is a popular JavaScript object document is a popular JavaScript object Variables of this object: alinkcolor, anchors[], applets[], bgcolor, cookie, domain, embeds[], fgcolor, forms[], images[], lastModified, linkColor, links[], location, plugins, referrer, title, URL, vlinkColor Variables of this object: alinkcolor, anchors[], applets[], bgcolor, cookie, domain, embeds[], fgcolor, forms[], images[], lastModified, linkColor, links[], location, plugins, referrer, title, URL, vlinkColor Methods of this object: clear(), close(), open(), write(), writeln() Methods of this object: clear(), close(), open(), write(), writeln()
24
24 Math Object Math object class cannot be instantiated and all its constants, variables and methods are static Thus, dot notation must use the class name Constants: Math.PI, Math.SQRT1_2, Math.SQRT2, Math.E, Math.LN10, Math.LN2, Math.LOG10E, Math.LOG2E Variables: NONE Methods: abs(), acos(), asin(), atan(), atan2(), ceil(), cos(), exp(), floor(), log(), max(), min(), pow(), random(), round(), sin(), sqrt(), tan()
25
25 Math Object Math Object Nesting Objects as Arguments Nesting Objects as Arguments //use methods of the Math object object document.write("Math.abs(-25) = " + Math.abs(-25) + " "); document.write("Math.acos(.5) = " + Math.acos(0.5) + " radians "); document.write("Math.acos(.5) = " + Math.acos(0.5) + " radians "); document.write("Math.asin(.5) = " + Math.asin(0.5) + " radians "); document.write("Math.atan(1) = " + Math.atan(1) + " radians "); document.write("Math.atan2(1,math.sqrt(3)) = " + Math.atan2(1,Math.sqrt(3)) + " radians "); document.write("Math.ceil(3.4) = " + Math.ceil(3.4) + " "); document.write("Math.cos(1.04719755119659) = " + Math.cos(1.04719755119659) + " "); document.write("Math.exp(2) = " + Math.exp(2) + " "); document.write("Math.floor(3.7) = " + Math.floor(3.7) + " "); document.write("Math.log(4.5) = " + Math.log(4.5) + " "); document.write("Math.max(3.5, -9) = " + Math.max(3.5,-9) + " "); document.write("Math.min(3.5, -9) = " + Math.min(3.5, -9) + " "); document.write("Math.pow(2, 3) = " + Math.pow(2, 3) + " "); document.write("Math.random() = " + Math.random() + " "); document.write("Math.round(3.1) = " + Math.round(3.1) + " "); document.write("Math.round(3.6) = " + Math.round(3.6) + " "); document.write("Math.sin(0.5235987755982989 ) = " + Math.sin(0.5235987755982989 ) + " "); document.write("Math.sqrt(4) = " + Math.sqrt(4) + " "); document.write("Math.tan(0.7853981633974483 ) = " + Math.tan(0.7853981633974483 ) + " "); document.write("Math.sqrt(4) = " + Math.sqrt(4) + " "); document.write("Math.tan(0.7853981633974483 ) = " + Math.tan(0.7853981633974483 ) + " ");
26
26 Date Object Date object can display the current date in a web page It has multiple constructors Constructors: Date(), Date(milliseconds), Date(string), Date(year, month, day, hours, minutes, seconds, milliseconds) Variables: NONE Methods: Bunch of set and get methods to assign values to the parameters of Date instance
27
27 Date Object Date Object <meta http-equiv="Content-Type“ ontent="text/html; charset=iso-8859-1" /> Date Formatting in JavaScript Date Formatting in JavaScript //use methods of the Date object <!-- Hide from ancient Browsers // Global Day Names and Month Names for Date Formatting Routines dayArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); monthArray = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); // 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) { 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;}
28
28 Date Object (Cont) d = new Date(); document.write(" Date Value = " + d); document.write(" Date.getYear() = " + d.getYear()); document.write(" Today = " + displayDate(d) +" "); 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(" Man walked on the moon on: " + displayDate(moonDate)); document.write(" The year was " + moonDate.getYear()); moonDate = new Date(1969, 6, 20); document.write(" Man walked on the moon on: " + displayDate(moonDate)); document.write(" The year was " + moonDate.getYear()); document.write(" ********************************* "); wtcDate = new Date(2001, 8, 11); document.write(" The world will remember " + displayDate(wtcDate)); document.write(" The year was " + wtcDate.getYear()); document.close(); // End Browser Hiding --> </script></head><body></body></html>
29
29 String Object String object has methods that allow us to control the appearance of string, and manipulate them String object has only one property for number of characters Variables: length Methods: anchor(), blink(), bold(), charAt(), concat(), fixed(), fontcolor(), fontsize(), italics(), link(), match(), replace(), search(), slice(), split(), strike(), sub(), substr(), sup(), toLowerCase(), toUpperCase()
30
30 String Object String Object Using String methods Using String methods //define a string str = "This is how the world ends!"; document.write("We apply the String methods to this text:"); document.write(" str = " + str + " "); document.write("================================"); //use the only variable of the String object document.write(" str.length = " + str.length); //use the methods of the String object document.write(" str.anchor('name') ==> " + str.anchor("name")); document.write(" str.big() ==> " + str.big()); document.write(" str.bold() ==> " + str.bold()); document.write(" str.charAt(3) ==> " + str.charAt(3)); document.write(" str.charCodeAt(3) ==> " + str.charCodeAt(3)); document.write(" str.concat('OK') ==> " + str.concat(" OK")); document.write(" str.fixed() ==> " + str.fixed()); document.write(" str.fontcolor('#FF0000') ==> " + str.fontcolor("#FF0000")); document.write(" str.fontsize(3) ==> " + str.fontsize(5));
31
31 String Object (Cont) document.write(" str.indexOf('s') ==> " + str.indexOf('s')); document.write(" str.italics() ==> " + str.italics()); document.write(" str.lastIndexOf('s') ==> " + str.lastIndexOf('s')); document.write(" str.link() ==> " + str.link()); document.write(" str.match('k') ==> " + str.match("k")); document.write(" str.replace('s', 'k') ==> " + str.replace("s", "k")); document.write(" str.search('s') ==> " + str.search("s")); document.write(" str.slice(7, 11) ==> " + str.slice(7,11)); document.write(" str.small() ==> " + str.small()); document.write(" str.split(' ') ==> " + str.split(" ")); words = str.split(" "); for (i=0; i<words.length; i++){ document.write(" " + words[i]); document.write(" " + words[i]); } //for document.write(" str.strike() ==> " + str.strike()); document.write(" str.sub() ==> " + str.sub()); document.write(" str.substring(7, 11) ==> " + str.substring(7, 11)); document.write(" str.substr(7, 4) ==> " + str.substr(7, 4)); document.write(" str.sup() ==> " + str.sup()); document.write(" str.toLowercase() ==> " + str.toLowerCase()); document.write(" str.toUpperCase() ==> " + str.toUpperCase());
32
32 Random colors Random colors <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" “ Random Color Generator Random Color Generator //generate a random hex color color = "#" + Math.floor(Math.random()*100) + Math.floor(Math.random()*100) + Math.floor(Math.random()*100); //display color hex code alert (color); //apply random color to text str = " This is randomly colored text "; document.write(str.fontcolor(color)); document.write(str.fontcolor(color));
33
33Summary Objects impart code reuse and modularity Objects impart code reuse and modularity Objects has attributes and behaviors Objects has attributes and behaviors Objects have to be created and used in a certain manner Objects have to be created and used in a certain manner Abstraction hides the details from the application Abstraction hides the details from the application Objects can be inherited and nested Objects can be inherited and nested DOM converts XHTML elements into JavaScript objects DOM converts XHTML elements into JavaScript objects JavaScript associates an array to object properties JavaScript associates an array to object properties document object has variables and methods document object has variables and methods Math object provides math functions and constants Math object provides math functions and constants Date object display the current date in a web page Date object display the current date in a web page String object allows text manipulations String object allows text manipulations
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.