370 likes | 576 Views
Using Object-Oriented JavaScript. CST 200- JavaScript 4 – 7 - 13. Objectives. In this chapter, you will: Study object-oriented programming Work with the Date , Number , and Math objects. Object Oriented Programming. Object-Oriented Programs model the world as a collection of objects
E N D
Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13
Objectives In this chapter, you will: • Study object-oriented programming • Work with the Date, Number, and Math objects
Object Oriented Programming • Object-Oriented Programs model the world as a collection of objects • Each object has properties and methods • Object-oriented programming (OOP) allows programmers to reuse code without having to copy or recreate it
Classes and Objects • In Object-Oriented Programming, the code, methods and attributes that make up an object are organized into a class • A class is a static piece of code – stored in a text file • An object is an instance of a class • An object exists within memory of a computer • A class can have many instances (objects) at the same time • Creating an object from a class is called instantiating an object
Browser Objects • Objects in the browser object model (window, document) are automatically created by the Web browser • We don't have to instantiate them to use them
Array Object • We have already worked with the Array JavaScript object • Example: var friends = new Array( "sam" , "bob" ); var colors = new Array( "red" , "green", "aqua" ); • Here, we create two Array objects (two instances of the Array class) one named friends, and another named colors Note the new keyword, tells the JavaScript interpreter we are creating a new object
Using the Date, Number, and Math Classes • Three most commonly used JavaScript classes: • Date, Number, and Math
Manipulating the Date and Time with the Date Class • Date class • Contains methods and properties for manipulating the date and time • Allows us to use a specific date or time element in JavaScript programs
Date Class (cont) • We can create a Date object using one of the following constructors: • A constructor is a special function used to create an object Table 6-2 Date class constructors
Date Class (cont’d.) • Example Date Objects: var today = new Date(); varindependenceDay = new Date(1776, 6, 4); store the current date and time store the specific date 7 / 4 / 1776
Date Class (cont’d.) • The date and time in a Date object is not updated over time like a clock • Date object contains the static (unchanging) date and time • Set at the moment the JavaScript code instantiates the object • We can manipulate the date and time using the Date class methods
Date Class (cont’d.) Table 6-3 Commonly used methods of the Date class (continues)
Date Class (cont’d.) Table 6-3 Commonly used methods of the Date class
Web Console Exercise #1 • Enter the following statements in Web Console: (not including comments) var today = new Date() today.getDay() // numeric value of day [0-6] today.getMonth() // numeric value of month [0-11] today.getFullYear() today.toString() var mill = new Date(2000,0,1) // Jan 1, 2000 mill.toString() Question: Create a new Date object called bday that contains your birthday
Date Class Example 1 • <script type="text/javascript"> • var today = new Date(); • varcurDay = today.getDay(); • if (curDay == 0) • document.write("Today is Sunday."); • else if (curDay == 1) • document.write("Today is Monday."); • else if (curDay == 2) • document.write("Today is Tuesday."); • else if (curDay == 3) • document.write("Today is Wednesday."); • else if (curDay == 4) • document.write("Today is Thursday."); • else if (curDay == 5) • document.write("Today is Friday."); • else if (curDay == 6) • document.write("Today is Saturday."); • </script>
Date Class Example 2 • include an array named months containing 12 elements assigned full text names of the months • <script type="text/javascript"> • var today = new Date(); • var months = new Array(); • months[0] = "January"; months[1] = "February"; • months[2] = "March"; months[3] = "April"; • months[4] = "May"; months[5] = "June"; • months[6] = "July"; months[7] = "August"; • months[8] = "September"; months[9] = "October"; • months[10] = "November"; months[11] = "December"; • var m = today.getMonth(); • varmonthName = months[ m ]; • document.write("<p>The current month is " • + monthName + ".</p>"); • </script>
Date Class Example 3 • Print out the minutes and seconds passed the hour: • <script type="text/javascript"> • var today = new Date(); • varmins = today.getMinutes(); • varsecs = today.getSeconds(); • document.write("<p>It is " + mins + " minutes and " • + secs + " seconds passed the hour.</p>"); • </script>
In Class Exercise (A) • Create a new JavaScript scriplet that performs the following tasks: • Create a Date object containing the current date and time • Display one of the following images based on the day of the week
In Class Exercise (B) • Create a new HTML form that allows the user to select a date value Create a function createDate() that gets the input from the user and creates a Date object Display the Date object in a popup window Save this page as dateForm.html
Date Arithmetic • We can find determine the difference between two dates by subtracting one date from another • Result will be represented in milliseconds • To convert the result into days, months or years, we must perform division to get the desired value type (months, years, days) • <script type="text/javascript"> • var x = new Date( 1990, 0 , 1); • var y = new Date( 1992, 3 , 10); • var diff = y - x; • var days = Math.floor( diff / ( 1000 * 60 * 60 * 24 ) ); • var years = Math.floor( days / 365 ); • document.write("<p>Difference " + days + " days.</p>"); • document.write("<p>Difference " + years + " years.</p>"); • </script>
Manipulating Numbers with the Number Class • Number class • Contains methods for manipulating numbers and properties containing static values • Can append the name of any Number class method or property to the name of an existing variable containing a numeric value
Number Class (cont’d.) • Using Number class methods Table 6-4 Number class methods
Manipulating Numbers with the Number Class (cont’d.) • The primary reason for using any of the “to” methods is to convert a number to a string value with a specific number of decimal places • toFixed() method • Converts a number to a string with a specified number of decimal places • Most useful Number class method Example: var total = salesTotal.toFixed(2);
Web Console Exercise #2 • Enter the following statements in Web Console: (not including comments) var x = 525.225 x x.toFixed(3) // convert to string with fixed # of decimals x.toFixed(1) x.toFixed(0) x (5.888).toFixed(1) (8.75 + 5).toFixed(0)
Performing Math Functions with the Math Class • Math class • Methods and properties for mathematical calculations • Cannot instantiate a Math object using a statement such as: var mathCalc = new Math() • Instead, use the Math object and one of its methods or properties directly in the code • Example: varcurNumber = 144; squareRoot = Math.sqrt(curNumber); // returns '12' document.write("The square root of " + curNumber + " is " + squareRoot);
Math Class (cont’d.) Table 6-7 Math class properties
Math Class (cont’d.) • Example: • Use the Math.PI property to calculate the area of a circle based on its radius • Also use the Math.round() method to round the value returned to the nearest whole number var radius = 25; var area = Math.round( Math.PI * radius * radius ); // return 1963 document.write("A circle with a radius of " + radius + " has an area of " + area);
Web Console Exercise #3 • Enter the following statements in Web Console: (not including comments) Math.abs( -20 ) var z = -25; Math.abs( z ) Math.ceil( 10.2 ); Math.floor(10.7 ); Math.max(20, 5) Math.min(12, 6) Math.random() Math.random() Math.round(582.56) // round to nearest integer var x = 70; Math.max( z , x )
Math Class Example <script type="text/javascript" > var x = Math.ceil( Math.random() * 6 ); document.write("random num between 1 and 6: "); document.write( x ); </script> Generate a random number between 1 and 6
Review Exercise #1 Generate a page with one button element that rolls a die and displays a popup message
Review Exercise #2 Update the webpage (dateForm.html) created earlier as below: • Add the following labels and textboxes for Age In Days and Age In Years • Update the createDate() function to calculate the Age In Days and Age in Years • Output the values to the corresponding textbox