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.

Slides:



Advertisements
Similar presentations
Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Python Objects and Classes
1 CS101 Introduction to Computing Lecture 41 Images & Animation (Web Development Lecture 14)
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
Session 8 JavaScript/Jscript: Objects Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
The Web Warrior Guide to Web Design Technologies
EIW: Javascript the Language1 The JavaScript Language.
JavaScript (Part 2) CS 183 4/13/2010. JavaScript (Part 2) Will cover: ◦ For.. In ◦ Events ◦ Try.. Catch, Throw ◦ Objects.
Chapter 16 Dynamic HTML and Animation The Web Warrior Guide to Web Design Technologies.
Javascript Document Object Model. How to use JavaScript  JavaScript can be embedded into your html pages in a couple of ways  in elements in both and.
XML Why is XML so popular? –It’s flexible –It enables you to create your own documents with elements (tags) that you define Non-XML example: This is a.
6.1 JavaScript Objects and Object- Oriented Programming (OOP)
JavaScript Programming an Introduction Prepared By P.D. Krolak and M.S. Krolak Based on material from JavaScript Unleashed (2nd Ed)
 2004 Prentice Hall, Inc. All rights reserved. Chapter 12 - JavaScript: Objects Outline 12.1 Introduction 12.2 Thinking About Objects 12.3 Math Object.
Lesson15. JavaScript Objects Objects encapsulate data (properties) and behavior(methods); the properties and the methods of an object are tied together.
1 CS101 Introduction to Computing Lecture 38 String Manipulations (Web Development Lecture 13)
1 CS101 Introduction to Computing Lecture 35 Mathematical Methods (Web Development Lecture 12)
Javascript and the Web Whys and Hows of Javascript.
Using Object-Oriented JavaScript CST 200- JavaScript 4 –
Scripting Languages.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
1 JavaScript: Objects and Object Models October 25, 2005 Slides modified from Internet & World Wide Web: How to Program (3rd) edition. By Deitel,
1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)
String Object.  Conundrum: I would like people to have more time on the revisions…  … but I don't have a lot of time myself for more grading  A1 Revision.
Chapter 4 JavaScript and Dynamic Web pages. Objectives Static Web pages Dynamic Web pages JavaScript Variables Assignments. JavaScript Functions –(prompt(“”,””)
Objective Static vs. Dynamic Web pages. Variables. Assignments. JavaScript Hierarchy of Objects JavaScript Functions (prompt(“”,””) Document.write(“”)
Chapter 8 Cookies And Security JavaScript, Third Edition.
JavaScript, Fourth Edition
CHAPTER 4 Java Script อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1.
Introduction to JavaScript Basharat Mahmood, Department of Computer Science, CIIT, Islamabad, Pakistan. 1.
Objects.  Java Script is an OOP Language  So it allows you to make your own objects and make your own variable types  I will not be going over how.
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
Using Client-Side Scripts to Enhance Web Applications 1.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Objects.
Chapter 5: Windows and Frames
M. Taimoor Khan Javascript Objects  Every data-type defined in Javascript is an object  It has a class definition for.
Created by, Author Name, School Name—State FLUENCY WITH INFORMATION TECNOLOGY Skills, Concepts, and Capabilities.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Scripting and Interactivity 이병희
Introduction to JavaScript Objects, Properties, Methods.
JavaScript, Fourth Edition Chapter 4 Manipulating the Browser Object Model.
JavaScript. JavaScript is the programming language of HTML and the Web. Easy to learn One of the 3 languages of all developers MUST learn: 1. HTML to.
1 Java Library Lecture 9 by Dr. Norazah Yusof. 2 Java Library Java has pre-defined classes that consist of the basic language classes in Java (organized.
ECA 225 Applied Interactive Programming ECA 225 Applied Online Programming javascript dates.
© 2007 D. J. ForemanJS-1 A Light Introduction for Non-programmers JavaScript for Beginners.
Chapter 12: Objects CIS 275—Web Application Development for Business I.
Java Script This is a first JavaScript example. This is a first JavaScript example.
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
Strings Robin Burke IT 130. Outline Objects Strings methods properties Basic methods Form validation.
JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to.
Basic Objects. Math Object  Math.cos( x ), x in radians  Math.sqrt ( x )  Math.pow ( x, y )  Math.ceil( x )  etc.
 2001 Prentice Hall, Inc. All rights reserved. Outline 1 JavaScript.
Chapter 4 Java Script – Part2. 2 Location object Properties Properties href – whole path will be displayed. ex: window.location.href ( see example 11)
Java Script: Objects (Chapter 12 in [2]). 2 Outline Introduction Introduction Thinking About Objects Thinking About Objects Math Object Math Object String.
11 JavaScript: Objects.
In this session, you will learn to:
SEEM4570 Tutorial 05: JavaScript as OOP
JavaScript for Beginners
14 A Brief Look at JavaScript and jQuery.
String, Math & Miscellaneous Methods & Properties
Using Built In Objects Kevin Harville.
JavaScript for Beginners
String, Math & Miscellaneous Methods & Properties
JavaScript for Beginners
Presentation transcript:

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

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

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

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 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 Inheriting and Nesting Objects

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 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 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 Document Object Model (DOM)

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 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 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 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 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 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( ) = " + Math.cos( ) + " "); 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( ) = " + Math.sin( ) + " "); document.write("Math.sqrt(4) = " + Math.sqrt(4) + " "); document.write("Math.tan( ) = " + Math.tan( ) + " "); document.write("Math.sqrt(4) = " + Math.sqrt(4) + " "); document.write("Math.tan( ) = " + Math.tan( ) + " ");

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 Date Object Date Object <meta http-equiv="Content-Type“ ontent="text/html; charset=iso " /> 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 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 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 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 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 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));

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