JavaScript - PowerPoint PPT Presentation

1 / 52
About This Presentation
Title:

JavaScript

Description:

The ceil () method always rounds a number up to the next largest whole number or ... Using ceil () is different from using the parseInt() function we saw in Chapter ... – PowerPoint PPT presentation

Number of Views:20
Avg rating:3.0/5.0
Slides: 53
Provided by: ahad6
Category:
Tags: javascript | ceil

less

Transcript and Presenter's Notes

Title: JavaScript


1
  • JavaScript
  • An Object-Based Language

2
  • The toLowerCase() and toUpperCase()
    MethodsChanging 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.

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

4
  • The Math Object
  • The Math object provides a number of useful
    mathematical functions and number manipulation
    methods. Well be taking a look at some of them
    here, but youll find the rest described in
    Appendix B.
  • The Math object is a little unusual in that
    JavaScript automatically creates it for you.
    Theres 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

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 Well look at a few of these methods
    now.

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
    its already positive.
  • For example, the following code would write the
    number 101 to the 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.

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.

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.

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.

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

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

14
  • Example JavaScript game.
  • Lets 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
    browsers Refresh button to get another set of
    random numbers.

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

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
    its a scientific application youre writing, the
    pow() method can often prove very useful.

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

18
(No Transcript)
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 its clear to JavaScript
    what object we expect to be created in the
    background. So for example
  • will lead JavaScript to assume, quite rightly,
    that its a string and any attempts to use the
    Number objects methods will fail.

20
  • The toFixed() Method
  • The toFixed () method is new and basically its
    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.

21
  • The toFixed() method doesnt 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 itd 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, its a good idea to double-check first
    if the browser supports it, like so

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.

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 000000 GMT. in the following example, the
    date is 31 January 2000 002000 GMT (that is, 20
    minutes past midnight).
  • its unlikely that youll 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.

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 153520
    and 20 milliseconds. You can specify just the
    date part if you wish and ignore the time.

25
  • Getting Date Values
  • Its 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.

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.

27
(No Transcript)
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 users computer.

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.

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 doesnt, 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.

31
  • How can we use this feature of setDate() and
    setMonth() to our advantage? Well, lets 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, its 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

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 todays date is the 15th of January and we use
    setDate (28), its 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.

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
    thats the third one, which we change to
  • We can use exactly the same principles for
    setMonth( ) as we have used for setDate ().

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, 13035 1 UTC).

35
(No Transcript)
36
(No Transcript)
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.

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 957. 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 1004.
  • 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.

39
  • JavaScript Classes
  • Weve seen that JavaScript provides a number of
    objects built into the language and ready for us
    to use. its a bit like a house thats 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 well 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.
    Lets say, for example, we were creating a cinema
    booking system. JavaScript doesnt come with any
    built-in cinema booking objects, so wed have to
    design our own.

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.

41
  • Where we have no need to store data but simply
    want functionality, such as the
    fixDecimalplaces() function we saw before, its
    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. its 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.

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.
    its useful when we want to initialize properties
    or the object in some way. We need to create a
    constructor even if we dont pass any parameters
    to it or it contains no code. in that case itd
    just be an empty definition. As with functions, a
    constructor can have zero or more parameters.

43
  • We used methods when we used JavaScripts
    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 dont need to
    declare our classs properties. We can simply go
    ahead and use properties in our class without
    letting JavaScript know in advance.

44
  • Defining a Class
  • Lets start by creating a class for a customers
    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 youd be right,
    its 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.

45
  • When looking at the code, the important thing to
    note is that the constructor functions name must
    match that of the class we are definingin 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 didnt simply by assigning a property a
    value, JavaScript creates it for us.

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
    wont tell us itll 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
    propertys value and allow us to set a propertys
    value. Now this may sound like hard work, but it
    can reduce bugs or at least make them easier to
    spot. Lets create a few property get/set methods
    for our customerBooking class.

47
(No Transcript)
48
  • Now we have defined a set and get method for each
    of our classs four properties, bookingId, film,
    customerName, and showDate. Lets look at how we
    created one of the methods, the getcustomerName
    () method.
  • The first thing we notice is that its a very odd
    way of defining a function. On the left we set
    the classs prototype propertys 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

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

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, wed write
  • Here, as with a String object, we have created
    two new objects and stored them in variables,
    firstBooking and secondBooking, but this time
    its a new object based on our class.

51
  • Lets call the getcustomerName() method of each
    of the two objects and write the results to the
    page.
  • And well see
  • written into the page from information contained
    in our class objects. Now lets put this together
    in a page.

52
  • Now lets put this together in an example.
  • Look at the Example link in the course web-site.
Write a Comment
User Comments (0)
About PowerShow.com