sahar mosleh california state university san marcospage 1 javascript an object-based language

52
Sahar Mosleh California State University San Marcos Page 1 JavaScript An Object-Based Language

Upload: tiffany-little

Post on 13-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 1

JavaScript An Object-Based Language

Page 2: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 2

The toLowerCase() and toUpperCase() Methods—Changing the Case of a String

• If we want to change the case of a string, for example to remove case sensitivity when comparing strings, we need the toLowercase() and touppercase() methods.

• Both of them return a string that is the value of the string in the String object, but with its case converted to either upper or lower depending on the method invoked. Any non-alphabetical characters remain unchanged by these functions.

• In the following example, we can see that by changing the case of both strings we can compare them without case sensitivity being an issue.

Page 3: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 3

• Even though toLowercase() and touppercase() don’t take any parameters, you must remember to put the two empty parentheses at the end, that is, (), if you want to call a method.

Page 4: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 4

The Math Object

• The Math object provides a number of useful mathematical functions and number manipulation methods. We’ll be taking a look at some of them here, but you’ll find the rest described in Appendix B.

• The Math object is a little unusual in that JavaScript automatically creates it for you. There’s no need to declare a variable as a Math object or define a new Math object before being able to use it, making it a little bit easier to use.

• The properties of the Math object include some useful math constants, such as the P1 property (giving the value 3.14159 and so on). We access these properties, as usual, by placing a dot after the object name (Math) and then writing the property name. For example, to calculate the area of a circle, we may use the following code:

Page 5: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 5

• For example, to calculate the area of a circle, we may use the following code:

• The methods of the Math object include some operations that are impossible, or complex, to perform using the standard mathematical operators (+, —, ‘, and /). For example, the cos() method returns the cosine of the value passed as a parameter We’ll look at a few of these methods now.

Page 6: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 6

The abs() Method

• The abs () method returns the absolute value of the number passed as its parameter Essentially, this means that it returns the positive value of the number So -1 is returned as 1, -4 as 4, and so on. However, 1 would be returned as 1 because it’s already positive.

• For example, the following code would write the number 101 to the page.

Page 7: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 7

The ceil() Method

• The ceil () method always rounds a number up to the next largest whole number or integer So 10.01 becomes 11, and -9.99 becomes- 9 (because -9 is greater than -10).

• The ceil () method has just one parameter, namely the number you want rounded up.

• Using ceil () is different from using the parseInt() function we saw in Chapter 2, because parseInt() simply chops off any numbers after the decimal point to leave a whole number, whereas ceil () rounds the number up.

• For example, the following code writes two lines in the page, the first containing the number 102 and the second containing the number 101.

Page 8: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 8

The floor() Method

• Like the ceil() method, the floor() method removes any numbers after the decimal point, and returns a whole number or integer.

• The difference is that floor() always rounds the number down. So if we pass 10.01 we would be returned 10, and if we pass -9.99, we will see -10 returned.

Page 9: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 9

The round() Method

• The round() method is very similar to ceil() and floor( ), except that instead of always rounding up or always rounding down, it rounds up only if the decimal part is 5 or greater, and rounds down otherwise.

• For example

• would write the numbers 45 and 44 to the page.

Page 10: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 10

Summary of Rounding Methods

• As we have seen, the ceil(), floor( ), and round() methods all remove the numbers after a decimal point and return just a whole number. However, which whole number they return depends on the method used: floor( ) returns the smallest, ceil() the highest, and round( ) the nearest equivalent integer.

• Remember that parseInt () is a native JavaScript function and not a method of the Math object, like the other methods presented in this table.

Page 11: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 11

Page 12: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 12

• The results of this number being passed to parseInt( ), ceil() floor() and round() will be displayed in the page formatted inside a table

Page 13: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 13

The random() Method

• The random () method returns a random floating-point number in the range between 0 and 1, where 0 is included and 1 is not. This can be very useful for displaying random banner images or for writing a

Page 14: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 14

Example: JavaScript game.

• Let’s look at how you would mimic the roll of a single dice. in the following page, ten random numbers are written to the page. Click the browser’s Refresh button to get another set of random numbers.

Page 15: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 15

• We want diceThrow to be between 1 and 6. The random () function returns a floating-point number between 0 and just under 1. By multiplying this number by 6, we get a number between 0 and just under 6. Then by adding 1, we get a number between 1 and just under 7. By using floor () to always round it down to the next lowest whole number, we can ensure that we’ll end up with a number between 1 and 6.

• If we wanted a random number between 1 and 100, we would just change the code so that Math. random() is multiplied by 100 rather than 6.

Page 16: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 16

The pow() Method

• The pow() method raises a number to a specified power it takes two parameters, the first being the number you want raised to a power, and the second being the power itself.

• For example, to raise 2 to the power of 8 (that is, to calculate 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2), we would write Math. pow(2, 8)

• The result being 256. Unlike some of the other mathematical methods, like sin(), cos(), which are not commonly used in web programming unless it’s a scientific application you’re writing, the pow() method can often prove very useful.

Page 17: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 17

• In the following example, we write a function using pow ( ) , which fixes the number of decimal places in a number.

Page 18: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 18

Page 19: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 19

Number Object

• As with the string object, Number objects need to be created before they can be used. To create a Number object, we can write

• However, as we have seen, we can also declare a number as primitive and use it as if it were a Number object, letting JavaScript do the conversion to an object for us behind the scenes. For example

• As with the String object, this technique is preferable so long as it’s clear to JavaScript what object we expect to be created in the background. So for example

• will lead JavaScript to assume, quite rightly, that it’s a string and any attempts to use the Number object’s methods will fail.

Page 20: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 20

The toFixed() Method

• The toFixed () method is new and basically it’s available in Netscape 6+ and IF 5.5+ only.

• The first document write() will output the following to the page:

• However, this is not the format we want; instead we want two decimal places, so on the next line, we enter

• We use the toFixed () method of the Number object to fix the number variable that itemCostAfterTax holds to two decimal places.

Page 21: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 21

• The toFixed() method doesn’t just chop off the digits not required; it also rounds up or down. In this case, it was 10.739, which rounds up to 10.74. If it’d been 10.732, it would have been rounded down to 10.73.Note that we can only fix a number from 0 to 20 decimal places.

• Because the method is only supported on newer browsers, it’s a good idea to double-check first if the browser supports it, like so:

Page 22: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 22

Date Objects

• The Date object handles everything to do with date and time in JavaScript. Using it, we can find out the date and time now, store our own dates and times, do calculations with these dates, and convert the dates into strings.

Page 23: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 23

Creating a Date Object

• We can declare and initialize a Date object in four ways. in the first method, we just declare a new Date object without initializing its value, in this case, the date and time value will be set to the current date and time on the PC on which the script is run.

• Secondly, we can define a Date object by passing the number of milliseconds since January 1, 1970 at 00:00:00 GMT. in the following example, the date is 31 January 2000 00:20:00 GMT (that is, 20 minutes past midnight).

• it’s unlikely that you’ll be using this way of defining a Date object very often, but this is how JavaScript actually stores the dates. The other formats for giving a date are simply for our convenience.

Page 24: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 24

• Next, we can pass a string representing a date, or a date and time. In the following example, we have “31 January 2000”.

• In the fourth and final way, we initialize the Date object by passing the following parameters separated by commas: year, month, day, hours, minutes, seconds, and milliseconds. For example

• This date is actually 31 January 2000 at 15:35:20 and 20 milliseconds. You can specify just the date part if you wish and ignore the time.

Page 25: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 25

Getting Date Values

• It’s all very nice having stored a date, but how do we get the information out again? Well, we just use the get methods. These are summarized in the following table.

Page 26: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 26

• For example, if we want to get the month in myDateObject, we can simply write

• All of the methods work in a very similar way, and all values returned are based on local time, that is, local to the machine the code is running on.

• Note that the getFullYear() method is available only in iF 4+ and NN 4.06+.

• In next example, we use the get date type methods we have been looking at to write the current day, month, and year to a web page.

Page 27: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 27

Page 28: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 28

Setting Date Values

• To change part of the date in a Date object, we have a group of set functions, which pretty much replicate the get functions described earlier, except that we are setting not getting the values. These are summarized in the following table.

• Note that for security reasons, there is no way for web-based JavaScript to change the current date and time on a user’s computer.

Page 29: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 29

• So, to change the year to 2001, the code would be

• Again, the setFullYear() method is available only in IE 4+ and NN 4.06+ browsers.

• Setting the date and month to the 27th of February looks like the following:

• One minor point to note here is that there is no direct equivalent to the getDay() method. Once the year, date, and month have been defined, the day is automatically set for you.

Page 30: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 30

Calculations and Dates

• Take a look at the following code:

• Surely there is some error, since when has January had 32 days? The answer to this query is that of course it doesn’t, and JavaScript knows that. instead JavaScript sets the date to 32 days from the 1st of January that is, it sets it to the 1st of February.

• The same also applies to the setMonth() method. if you set it to a value greater than 11, the date automatically rolls over to the next year. So if we use setMonth( 12), that will set the date to January of the next year, and similarly setMonth(13) is February of the next year.

Page 31: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 31

• How can we use this feature of setDate() and setMonth() to our advantage? Well, let’s say we want to find out what date it is 28 days from now. Given that different months have different numbers of days and that we could roll over to a different year, it’s not as simple a task as it might first seem. Or at least that would be the case if it were not for setDate() . The code to achieve this task is as follows:

Page 32: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 32

• First we get the current system date by setting the nowDate variable to a new Date object with no initialization value, in the next line we put the current day of the month into a variable called currentDay. Why? Well, when we use setDate () and pass it a value outside of the maximum number of days for that month, it starts from the first of the month and counts that many days forward. So, if today’s date is the 15th of January and we use setDate (28), it’s not 28 days from the 15th of January, but 28 days from the 1st of January. What we want is 28 days from the current date, so we need to add the current date onto the number of days ahead we want. So, we want setDate (15 + 28) . In the third line we set the date to the current date, plus 28 days. We stored the current day of the month in currentDay, so now we just add 28 to that to move 28 days ahead.

Page 33: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 33

• If we want the date 28 days prior to the current date, we just pass the current date minus 28. Note that this will most often be a negative number We need to change only one line, and that’s the third one, which we change to

• We can use exactly the same principles for setMonth( ) as we have used for setDate ().

Page 34: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 34

Getting Time Values

• Retrieving the individual time data works much like the get methods for date values. The methods we use here are:

gethours()getMinutes()getseconds()getMilliseconds ()toTimestring()

• These methods return respectively the hours, minutes, seconds, milliseconds, and full time of the specified Date object, where the time is based on the 24-hour clock: 0 for midnight and 23 for 11 p.m.

• toTimestring() is similar to the toDatestring() method in that it returns an easily readable string, except in this case, it contains the time (for example, “13:03:5 1 UTC”).

Page 35: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 35

Page 36: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 36

Page 37: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 37

Setting Time Values

• When we want to set the time in our Date objects, we have a series of methods similar to those used for getting the time:

setlHours() setMinutes() setseconds()

setMilliseconds ()

• Again, the setMilliseconds () method is available only in IE 4+ and NN 4.06+ browsers.

Page 38: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 38

• First we declare the nowDate variable and assign it to a new Date object, which will contain the current date and time. in the following two lines we set the hours to 9 and the minutes to 57. We show the date and time using an alert box, which should show a time of 9:57. The minutes are then set to 64 and again an alert box is used to show the date and time to the user. Now the minutes have rolled over the hour so the time shown should be 10:04.

• If the hours were set to 23 instead of 9, setting the minutes to 64 would not just move the time to another hour but also cause the day to change to the next date.

Page 39: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 39

JavaScript Classes

• We’ve seen that JavaScript provides a number of objects built into the language and ready for us to use. it’s a bit like a house that’s built already and we can just move on in. However, what if we want to create our own house, design it ourselves for our own specific needs? In that case we’ll use an architect create technical drawings and plans that provide the template for the new house, the builders use the plans to tell them how to create the house.

• JavaScript allows us to be an architect and create the templates for our own objects to our own specification to fill our specific needs. Let’s say, for example, we were creating a cinema booking system. JavaScript doesn’t come with any built-in cinema booking objects, so we’d have to design our own.

Page 40: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 40

• What we need to do is create objects modeled round the real world. So for a simple cinema booking system, we might have an object representing customers’ booking details and an object for the cinema where the bookings have been made. As well as allowing us to store information, we can create our own methods for an object. So for a booking system, we might want an “add new booking” method or a method that gets details of all the bookings currently made.

Page 41: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 41

• Where we have no need to store data but simply want functionality, such as the fixDecimalplaces() function we saw before, it’s generally easier just to have a code library rather than create a special object.

• The template used to build a house. Before we can use our new object type, we need to define its class, methods, and properties. The important distinction is that when we define our class, no object based on that is created. it’s only when we create an instance of our class using the new keyword that an object of that class type, based on our class blueprint or prototype, is created.

Page 42: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 42

• A class consists of three things:

A constructor

Method definitions

Properties

• A constructor is a method called every time one of our objects based on this class is created. it’s useful when we want to initialize properties or the object in some way. We need to create a constructor even if we don’t pass any parameters to it or it contains no code. in that case it’d just be an empty definition. As with functions, a constructor can have zero or more parameters.

Page 43: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 43

• We used methods when we used JavaScript’s built-in objects; now we get the chance to use classes to define our own methods performing specific tasks. Our class will specify what methods we have and the code that they execute. Again we have used properties of built-in objects and now get to define our own. We don’t need to declare our class’s properties. We can simply go ahead and use properties in our class without letting JavaScript know in advance.

Page 44: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 44

Defining a Class

• Let’s start by creating a class for a customer’s booking. Our class will be called the CustomerBooking class. The first thing we need to do is create the class constructor.

• The constructor for our class is shown here:

• Your first thought might be that what we have here is simply a function, and you’d be right, it’s not until we start defining the CustomerBooking class properties and methods that it becomes a class. This is in contrast to some programming languages, which have a more formal way of defining classes.

Page 45: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 45

• When looking at the code, the important thing to note is that the constructor function’s name must match that of the class we are defining—in this case the customerBooking class. That way when a new instance of our class as an object (termed an object instance) is created, this function will be called automatically. Note we have four parameters for our constructor function, and these are used inside the class itself. However, note that we use the this keyword. For example

• Inside a constructor function or within a class method, the this keyword will refer to that object instance of our class. Here we refer to the customerName property of this class object, and we set it to equal the customerName parameter If you have used other object-oriented programming languages, you might wonder where we defined this customerName property. The answer is we didn’t; simply by assigning a property a value, JavaScript creates it for us.

Page 46: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 46

• JavaScript creates it as it needs to. The same is true if we use the object with a property never mentioned in our class definition. All this free property creation might sound great, but it has drawbacks, the main one being that if we accidentally misspell a property name, JavaScript won’t tell us; it’ll just create a new property with the misspelled name, something that can make it difficult to track bugs. One way around this problem is to create methods that get a property’s value and allow us to set a property’s value. Now this may sound like hard work, but it can reduce bugs or at least make them easier to spot. Let’s create a few property get/set methods for our customerBooking class.

Page 47: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 47

Page 48: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 48

• Now we have defined a set and get method for each of our class’s four properties, bookingId, film, customerName, and showDate. Let’s look at how we created one of the methods, the getcustomerName () method.

• The first thing we notice is that it’s a very odd way of defining a function. On the left we set the class’s prototype property’s getCustomerName to equal a function, which we then define immediately afterwards. In fact, JavaScript supplies most objects with a prototype property, which allows new properties and methods to be created. So, whenever we want to create a method for our class, we simply write

Page 49: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 49

• We’ve created our class, but how do we now create new objects based on that class? Well, we look at this in the next section.

Page 50: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 50

Creating and Using Class Object Instances

• We create instances of our classes in the same way we created instances of built-in JavaScript classes:

• using the new keyword. So to create a new instance of our customerBooking class, we’d write

• Here, as with a String object, we have created two new objects and stored them in variables, firstBooking and secondBooking, but this time it’s a new object based on our class.

Page 51: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 51

• Let’s call the getcustomerName() method of each of the two objects and write the results to the page.

• And we’ll see

• written into the page from information contained in our class objects. Now let’s put this together in a page.

Page 52: Sahar Mosleh California State University San MarcosPage 1 JavaScript An Object-Based Language

Sahar Mosleh California State University San Marcos Page 52

• Now let’s put this together in an example.

• Look at the Example link in the course web-site.