33
Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

Embed Size (px)

Citation preview

Page 1: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

Using Object-Oriented JavaScript

CST 200- JavaScript4 – 7 - 13

Page 2: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

2

Objectives

In this chapter, you will:

• Study object-oriented programming

• Work with the Date, Number, and Math objects

Page 3: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

3

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

Page 4: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

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

4

Page 5: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

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

5

Page 6: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

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

6

Note the new keyword, tells the JavaScript interpreter we are

creating a new object

Page 7: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

7

Using Built-In JavaScript Classes

Page 8: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

8

Using the Date, Number, and Math Classes

• Three most commonly used JavaScript classes:– Date, Number, and Math

Page 9: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

9

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

Page 10: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

10

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

Page 11: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

11

Date Class (cont’d.)

• Example Date Objects:

var today = new Date();

var independenceDay = new Date(1776, 6, 4);

store the current date and time

store the specific date 7 / 4 / 1776

Page 12: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

12

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

Page 13: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

13

Table 6-3 Commonly used methods of the Date class (continues)

Date Class (cont’d.)

Page 14: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

14

Table 6-3 Commonly used methods of the Date class

Date Class (cont’d.)

Page 15: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

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

15

Question: Create a new Date object called bday that contains your birthday

Page 16: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

16

<script type="text/javascript">var today = new Date();var curDay = 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 1

Page 17: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

17

<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();var monthName = months[ m ];

document.write("<p>The current month is "+ monthName + ".</p>");

</script>

Date Class Example 2• include an array named months containing 12

elements assigned full text names of the months

Page 18: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

18

<script type="text/javascript">var today = new Date();var mins = today.getMinutes();var secs = today.getSeconds();

document.write("<p>It is " + mins + " minutes and " + secs + " seconds passed the hour.</p>");

</script>

Date Class Example 3

• Print out the minutes and seconds passed the hour:

Page 19: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

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

19

0 d0.jpg 4 d4.jpg

1 d1.jpg 5 d5.jpg

2 d2.jpg 6 d6.jpg

3 d3.jpg

Page 20: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

In Class Exercise (B)• Create a new HTML form that allows the user to

select a date value

20

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

Page 21: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

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)

21

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

Page 22: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

22

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

Page 23: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

23

Number Class (cont’d.)

• Using Number class methods

Table 6-4 Number class methods

Page 24: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

24

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

Page 25: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

Web Console Exercise #2

• Enter the following statements in Web Console: (not including comments)

var x = 525.225xx.toFixed(3) // convert to string with fixed # of decimalsx.toFixed(1)x.toFixed(0)x(5.888).toFixed(1)(8.75 + 5).toFixed(0)

25

Page 26: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

26

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:var curNumber = 144;squareRoot = Math.sqrt(curNumber); // returns '12'document.write("The square root of " + curNumber

+ " is " + squareRoot);

Page 27: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

27

Math Class (cont’d.)

Page 28: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

28

Table 6-7 Math class properties

Math Class (cont’d.)

Page 29: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

29

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 1963document.write("A circle with a radius of " + radius

+ " has an area of " + area);

Page 30: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

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 integervar x = 70;Math.max( z , x )

30

Page 31: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

Math Class Example

31

<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

Page 32: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

Review Exercise #1

Generate a page with one button element that rolls a die and displays a popup message

32

Page 33: Using Object-Oriented JavaScript CST 200- JavaScript 4 – 7 - 13

Review Exercise #2

Update the webpage (dateForm.html) created earlier as below:

33

1. Add the following labels and textboxes for Age In Days and Age In Years

2. Update the createDate() function to calculate the Age In Days and Age in Years

3. Output the values to the corresponding textbox