330 likes | 499 Views
CMPS 211 JavaScript. Topic 4 Objects. Goals and Objectives. 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
E N D
CMPS 211 JavaScript Topic 4 Objects
Goals and Objectives • 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 • Importance of objects in web programming • Definition • Concepts • Implementation • Nesting objects • DOM • Associative arrays • Built-in objects: document, Math, Date, String
Chapter Headlines • 1 Introduction • Is JavaScript and OO language? Why should it be? • 2 Definition • Is car an object? • 3 Creation and Use • Does JavaScript create and use a car as in real life? • 4 Concepts • What is about objects? • 5 Inheriting and Nesting Objects • Object family members save time
Chapter Headlines • 6 Document Object Modeling (DOM) • Checkout this model before writing JavaScript cod8 Document Object • Find out what makes a web page in JavaScript • 9 Math Object • And you thought JavaScript cannot do math • 10 Date Object • Create a real time date in a web page • 11 String Object • JavaScript makes text manipulation easy
Introduction • Object oriented programming (OOP) resembles real life • OOP allows code reuse, and modularity • OO code is easy to follow • Objects have properties and behaviors that translate to variables and functions in programs • JavaScript is based on OO paradigm • JavaScript is a powerful OOP language in the context of web development
Definition • Object is the basic unit in OO code • Objects have: • Attributes they become variables in an OOP • Behaviors they become methods (functions) in an OOP • JavaScript can create user-defined objectsExamples: car, house, bank accounts, etc. • JavaScript also provides it own predefined objectsExamples: Date, Math, String, etc. Object Definition Methods Bank account account number deposit account owner withdrawal account address account balance
Creation and Use • Object creation and use is essential to realize all benefits of OOP • OOP languages use three concepts to implement objects: • Classes • Instantiation • Dot notation • Classes define objects • Instantiation creates them • Dot notation uses them • objectName.propertyName; • objectName.methodName(); • JavaScript uses these concepts for object creation and use
A House Object <?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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>A House object</title> <script language="javascript"> //define House object function House (rms, stl, yr, garg) { this.rooms = rms; //attribute this.style = stl; //attribute this.yearBuilt = yr; //attribute this.hasGarage = garg; //attribute }//House //Create a house instance myHouse = new House(5, "colonial", 1990, true); //Use house instance document.write("My house has " + myHouse.rooms + " rooms<br />"); document.write("My house style is " + myHouse.style + "<br />"); document.write("My house was built in " + myHouse.yearBuilt +"<br />"); document.write("My house has a garage: " + myHouse.hasGarage); </script> </head> <body> </body> </html>
Creation and Use • Classes hold object definition, attributes, methods, constructors • Constructor Function • Special method to create and initialize instances • Instantiation • new keyword is used to create an instance of an object • Dot notation • Allows an instance to access its class members • The this reference • Powerful concept and makes code efficient and elegant • Used to reference class members within constructor function • To reference the current object
<?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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>A House object</title> <script language="javascript"> //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<br />"); document.write("My house style is " + myHouse.style + "<br />"); document.write("My house was built in " + myHouse.yearBuilt + "<br />"); document.write("My house has a garage: " + myHouse.hasGarage); document.write("My house living space is: " + myHouse.livingSpace(30, 70, 2) + " square feet<br />"); document.write(myHouse.maintain()); </script> </head><body></body> </html> Create & Use
‘this’ Reference <?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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>The this Reference</title> <script language="javascript"> //define Dog object function Dog (name, age){ 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; compareDogs()
‘this’ Reference (cont) //Create four dog instances myDog = new Dog("Splinter", 4); yourDog = 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) + "<br />"); document.write("====================================<br />"); //these two dogs are equal Document.write("Comparing your dog and John's dog produces: " + yourDog.compareDogs(johnDog) + "<br />"); document.write("====================================<br />"); //these two dogs are not equal document.write("Comparing John's dog and Lisa's dog produces: " + johnDog.compareDogs(lisaDog)); </script> </head> <body> </body> </html>
Concepts • OO concepts include • Abstraction • Class • Constructors • Encapsulation • Instances • Inheritance • Abstraction means thinking at higher level • Abstraction hides details of implementation that may not be relevant to an application • Data and functional abstraction exist
Inheriting and Nesting Objects • Inheritance allows one object to inherit variables and methods from another objects • The class that we inherit from is superclass • The class that inherits is subclass • Subclass can have additional methods and variables • Classes at the bottom of the tree are more specific • JavaScript implements inheritance through association • In association an object is used in definition of another object as an attribute • Objects are nested in two different ways • Passing objects as arguments to another’s constructor function • Prototyping an object inside the another’s constructor function
Passing Objects <?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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Nesting Objects as Arguments</title> <script language="javascript"> //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 + "<br />"); document.write ("Manager department is " + salesManager.employee.department + "<br />"); document.write ("Manager " + salesManager.employee.name + " manages " + salesManager.staff + " people"); </script> </head> <body> </body> </html>
Prototyping Objects <?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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <meta name="author" content="zeid" /> <meta name="generator" content="AceHTML 5 Freeware" /> <!-- Compare the code of this example with the code of Slide 16 to understand the difference between nesting objects via arguments or via prototyping --> <title>Nesting Objects by Prototyping</title> <script language="javascript"> //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 + "<br />"); document.write ("Manager department is " + salesManager.department + "<br />"); document.write ("Manager " + salesManager.name + " manages " + salesManager.staff + " people"); </script> </head> <body> </body> </html>
Document Object Model (DOM) • 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 • Every web page has the following objects: • Navigator properties for name and version of the browser • Window for the browser window and every frame of a set • Document refers to the web page currently displayed • Location contains the web page URL • History has the previously requested URLs • We must use the dot notation chain to access object properties
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 indexExample: 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
Associative Arrays <?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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Nesting Objects as Arguments</title> <script language="javascript"> //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 //Use associative array to print any object properties
Associative Arrays (Cont) function print(obj, objName){ props = ""; for (i in obj){ if (obj[i] instanceof Object){ for (j in obj[i]) props += objName + "." + j + " = " + obj[i][j] + "<br />"; } //if else props += objName + "." + i + " = " + obj[i] + "<br />"; } //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<br />"); document.write ("Manager " + salesManager.employee['name'] + " manages " + salesManager['staff'] + " people<br />"); document.write ("Manager name is " + salesManager.employee['name'] + "<br />"); document.write ("Manager department is " + salesManager.employee['department'] + "<br />"); document.write("<br />===========================<br />"); //print slaesmanager another way document.write("Printing object proeperites using numbers as indexes for the associative array elements<br />"); document.write(print(salesManager, "salesmanager")); </script> </head> <body> </body> </html>
Document 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 • Methods of this object:clear(), close(), open(), write(), writeln()
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()
Math Object <?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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Nesting Objects as Arguments</title> <script language="javascript"> //use methods of the Math object object document.write("Math.abs(-25) = " + Math.abs(-25) + "<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.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.ceil(3.4) = " + Math.ceil(3.4) + "<br />"); document.write("Math.cos(1.04719755119659) = " + Math.cos(1.04719755119659) + "<br />"); document.write("Math.exp(2) = " + Math.exp(2) + "<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.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.pow(2, 3) = " + Math.pow(2, 3) + "<br />"); document.write("Math.random() = " + Math.random() + "<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.sin(0.5235987755982989 ) = " + Math.sin(0.5235987755982989 ) + "<br />"); document.write("Math.sqrt(4) = " + Math.sqrt(4) + "<br />"); document.write("Math.tan(0.7853981633974483 ) = " + Math.tan(0.7853981633974483 ) + "<br />"); </script> </head> <body> </body> </html>
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
Date Object <?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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type“ ontent="text/html; charset=iso-8859-1" /> <title>Date Formatting in JavaScript</title> <script language="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 // e.g. Thursday Novemebr 13, 2003 function displayDate(inDate) { str = dayArray[inDate.getDay()]; str += " " + monthArray[inDate.getMonth()]; str += " " + inDate.getDate(); // Browsers return different values for Date.getYear() // (Netscape 4.x) always show 2 digit years // (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! theYear = inDate.getYear(); str += ", " + (theYear + (theYear < 1000 ? 1900 : 0)); return str; }
Date Object (Cont) d = new Date(); document.write("<BR>Date Value = " + d); document.write("<BR>Date.getYear() = " + d.getYear()); document.write("<BR><B>Today = " + displayDate(d) +"</B>"); document.write("<BR>*********************************<BR>"); // Show the difference between a 19xx year and 20xx year moonDate = new Date(1969, 6, 20); document.write("<BR>Man walked on the moon on: " + displayDate(moonDate)); document.write("<BR>The year was " + moonDate.getYear()); document.write("<BR>*********************************<BR>"); wtcDate = new Date(2001, 8, 11); document.write("<BR>The world will remember " + displayDate(wtcDate)); document.write("<BR>The year was " + wtcDate.getYear()); document.close(); // End Browser Hiding --> </script> </head> <body> </body> </html>
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()
String Object <?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"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Using String methods</title> <script language="javascript"> //define a string str = "This is how the world ends!"; document.write("We apply the String methods to this text:"); document.write("<h2>str = " + str + "</h2>"); document.write("================================"); //use the only variable of the String object document.write("<br />str.length = " + str.length); //use the methods of the String object document.write("<br />str.anchor('name') ==> " + str.anchor("name")); document.write("<br />str.big() ==> " + str.big()); document.write("<br />str.bold() ==> " + str.bold()); document.write("<br />str.charAt(3) ==> " + str.charAt(3)); document.write("<br />str.charCodeAt(3) ==> " + str.charCodeAt(3)); document.write("<br />str.concat('OK') ==> " + str.concat(" OK")); document.write("<br />str.fixed() ==> " + str.fixed()); document.write("<br />str.fontcolor('#FF0000') ==> " + str.fontcolor("#FF0000")); document.write("<br />str.fontsize(3) ==> " + str.fontsize(5));
String Object (Cont) document.write("<br />str.indexOf('s') ==> " + str.indexOf('s')); document.write("<br />str.italics() ==> " + str.italics()); document.write("<br />str.lastIndexOf('s') ==> " + str.lastIndexOf('s')); document.write("<br />str.link() ==> " + str.link()); document.write("<br />str.match('k') ==> " + str.match("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.slice(7, 11) ==> " + str.slice(7,11)); document.write("<br />str.small() ==> " + str.small()); document.write("<br />str.split(' ') ==> " + str.split(" ")); words = str.split(" "); for (i=0; i<words.length; i++){ document.write("<br />" + words[i]); } //for document.write("<br />str.strike() ==> " + str.strike()); document.write("<br />str.sub() ==> " + str.sub()); 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.sup() ==> " + str.sup()); document.write("<br />str.toLowercase() ==> " + str.toLowerCase()); document.write("<br />str.toUpperCase() ==> " + str.toUpperCase()); </script> </head> <body> </body> </html>
Random colors <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" “ <!-- Generated by AceHTM http://freeware.acehtml.com --> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Random Color Generator</title> <script language="javascript"> //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 = "<h1>This is randomly colored text</font></h1>"; document.write(str.fontcolor(color)); </script> </head> <body></body></html>
Summary • Objects impart code reuse and modularity • Objects has attributes and behaviors • Objects have to be created and used in a certain manner • Abstraction hides the details from the application • Objects can be inherited and nested • DOM converts XHTML elements into JavaScript objects • JavaScript associates an array to object properties • document object has variables and methods • Math object provides math functions and constants • Date object display the current date in a web page • String object allows text manipulations