Docstoc

Ch12

Document Sample
Ch12 Powered By Docstoc
					Internet Systems




Chapter 12. JavaScript: Objects
We’ll use JavaScript to manipulate all kinds of objects.

This chapter is a more principled treatment of objects.
   This chapter looks a several built-in objects.
   The chapters on Dynamic HTML introduce many objects
     provided by the browser that allow scripts to interact with
     elements of an HTML document.

Objects we’ve already seen:
   document
   window
      Array (constructor)

Math Object
Some methods of object Math – See the text (Fig. 12.1, p. 406) for
  the common methods.
   Let x and y evaluate to numeric values.
     Math.max( x, y )
        Math.min( x, y )
        Math.sqrt( x )

Some constants – See the text (Fig. 12.2, pp. 406-407) for the
  common constants.
    Math.E is e, the base of the natural logarithms.
        Math.LN10 is loge 10, i.e., ln 10.
        Math.PI is π.




                                    98
Internet Systems




Example:

<script type = "text/javascript">
  var x = 3, y = 5;

    document.writeln( "<p>Math.E = " +
                      Math.E + "</p>" );
    document.writeln( "<p>Math.LN10 = " +
                      Math.LN10 + "</p>" );
    document.writeln( "<p>Math.PI = " +
                      Math.PI + "</p>" );

    document.writeln( "<p>x = " + x + ", y = "
             + y + "</p>" );

  document.writeln( "<p>Math.max( x, y ) = " +
                   Math.max( x, y ) + "</p>" );
  document.writeln( "<p>Math.pow( x, y ) = " +
                   Math.pow( x, y ) + "</p>" );
  document.writeln( "<p>Math.sqrt( x ) = " +
                    Math.sqrt( x ) + "</p>" );
</script>


   Math.E = 2.718281828459045
   Math.LN10 = 2.302585092994046
   Math.PI = 3.141592653589793
   x = 3, y = 5
   Math.max( x, y ) = 5
   Math.pow( x, y ) = 243
   Math.sqrt( x ) = 1.7320508075688772




                               99
Internet Systems




String Objects
A string is a sequence of characters, a unit of type String.

String literals or string constants (or anonymous String objects)
   are sequences of characters in double or single quotes – e.g.,
    “Fred Smith”
    ‘(336) 334-7245’

A string may be assigned to a variable – e.g.,
    var color = “blue”;
Strings are compared with the usual relational operators (lex order),
       <, <=, >, >=, ==, !=

Some String methods – see the text (Fig. 12.3, pp. 408-409) for a
    complete list.
  Let
    n (with or without subscripts) be a natural number,
    uc (with or without subscripts) be a Unicode value, and
    str be a string.
  Let s be an arbitrary string.
    For the examples, let s be “ABCDEF”.

  s.concat( str ) returns the concatenation of s and str (in
    that order).
   s.concat(“GHIJKL”) returns “ABCDEFGHIJKL”.

  s.toLowerCase( ) returns a string identical to s except that
    all uppercase letters are converted to lowercase.
   s.toLowerCase( ) returns “abcdef”.




                                   100
Internet Systems




  String.fromCharCode(uc1, …, ucn) converts a list of
    Unicode values into a string containing the corresponding
    characters.
   String.fromCharCode(65, 66, 67 ) returns “ABC”.

  s.indexOf( str ) returns the index of the leftmost occurrence
    of str as a substring in s, or –1 if str is not a substring of s.
    (0 is the first index.)
   s.indexOf( “C” ) returns 2.

  s.indexOf( str, n ) is as above except that the search for str
    starts at index n of s.

  s.lastIndexOf( str ) returns the index of the rightmost
    occurrence of str in s, or –1.

  s.substr( n ) returns the substring of s starting at index n
    (and going to the end of s).
   s.substr( 3 ) returns “DEF”.

  s.substr( n1, n2 ) returns the substring of s starting at index
    n1 and of length n2 (shorter if s is not long enough).
  s.split( str ) returns the array of strings consisting of the
    substrings of s split up by the delimiter string str.
   Let s1 be “the tall man”.
    s1.split( “ “ ) returns [“the”, “tall”, “man”].

In addition, where ar is an array of strings:
  ar.join( str )          returns the string that results from
    concatenating the elements of ar with str separating them.
  For example, if ar is [“the”, “tall”, “man”], then
       ar.join( “_” ) returns “the_tall_man”.


                                  101
Internet Systems




Example:

<script type = "text/javascript">
  var s = "ABCDEF",
       s1 = "the tall man";
  var s2;
  var ar;

    document.writeln( "<p>s = " + s + "</p>" );
    document.writeln( "<p>s.concat( 'GHIJKL' ) = "
                + s.concat( "GHIJKL" ) + "</p>" );
    document.writeln( "<p>s.toLowerCase( ) = "
                + s.toLowerCase( ) + "</p>" );
    document.writeln( "<p>s.charAt( 1 ) = "
                + s.charAt( 1 ) + "</p>" );
    document.writeln( "<p>s.charCodeAt( 0 ) = "
                + s.charCodeAt( 0 ) + "</p>" );

    s2 = String.fromCharCode( 65,66,67,68,69,70 );
    document.write( "<p>String.fromCharCode( "
             + "65,66,67,68,69,70 ) = " );
    document.writeln( s2 );
    document.writeln( "</p>" );

    document.writeln( "<p>s.indexOf( 'C' ) = "
                  + s.indexOf( "C" ) + "</p>" );

    document.writeln( "<p>s1 = " + s1 + "</p>" );
    document.writeln( "<p>s1.lastIndexOf('a', 9) = "
              + s1.lastIndexOf( "a", 9 ) + "</p>" );
    document.writeln( "<p>s1.substr( 4 ) = "
                  + s1.substr( 4 ) + "</p>" );
    document.writeln( "<p>s1.substr( 4, 4 ) = "
                  + s1.substr( 4, 4 ) + "</p>" );

    ar = s1.split( " " );
    document.write( "<p>The words in s1: " );

                   Continued next page


                            102
Internet Systems




                       Continued from previous page
    for ( var i = 0; i < ar.length - 1; i ++ )
      document.write( " Word " + i + ": " +
                      ar[ i ] + "," );

    document.write( " Word " + ( ar.length - 1 )
                   + ": " + ar[ ar.length-1 ] );
    document.writeln( "</p>" );

    document.write( "<pre>” +
           “These words joined with new lines:\n" );
    document.write( ar.join( "\n" ) + "</pre>" );

</script>


   s = ABCDEF
   s.concat( 'GHIJKL' ) = ABCDEFGHIJKL
   s.toLowerCase( ) = abcdef
   s.charAt( 1 ) = B
   s.charCodeAt( 0 ) = 65
   String.fromCharCode( 65,66,67,68,69,70 ) = ABCDEF
   s.indexOf( 'C' ) = 2
   s1 = the tall man
   s1.lastIndexOf( 'a', 9 ) = 5
   s1.substr( 4 ) = tall man
   s1.substr( 4, 4 ) = tall
   The words in s1: Word 0: the, Word 1: tall, Word 2: man
   These words joined with new lines:
   the
   tall
   man



                                   103
Internet Systems




XHTML Markup Methods
Some string methods that generate HTML markup tags – see the
  text (p. 409, the last part of Fig. 12.3) for a complete list.
  Let
    n be a natural number,
    str be a string, and
    url be a URL.
  Let s be any arbitrary string.
    For the examples, let s be “abc”.

  s.big( ) wraps s in <big> … </big> tags.
   s.big( ) returns “<big>abc</big>”.

  s.fontsize( n ) wraps s in
    <font size = “n”> … </font> tags.
   s.fontsize( 6 ) returns
         “<font size = ‘6’>abc</font>”.

  s.anchor( str ) wraps s in
    <a name = str> … </a> tags.
   s.anchor( “top” ) returns
     “<a name = ‘top’>abc</a>”.

  s.link( url ) wraps s in
    <a href = “url”> … </a> tags.
    s.link( “#top” ) returns
      “<a href = ‘#top’>abc</a>”.




                                104
Internet Systems




Example:


<script type = "text/javascript">
  var s = "abc",
       s1 = "this is an anchor",
       s2 = "this is a link";

  document.writeln( "<p>s = " + s + ", s1 = "
           + s1 + ", s2 = " + s2 + "</p>" );
  document.writeln( "<p>s1.anchor( 'top' ): " +
           s1.anchor( "top" ) + "</p>" );
  document.writeln( "<p>s.big( ): " +
           s.big( ) + "</p>" );
  document.writeln( "<p>s.fontsize( 6 ): " +
           s.fontsize( 6 ) + "</p>" );
  document.writeln( "<p>s2.link( '#top' ): " +
           s2.link( "#top" ) + "</p>" );
</script>


   s = abc, s1 = this is an anchor, s2 = this is a link
   s1.anchor( 'top' ): this is an anchor
   s.big( ): abc


   s.fontsize( 6 ):   abc
   s2.link( '#top' ): this is a link




                                       105
Internet Systems




Date Objects
The Date object provides methods for date and time processing.

We use the following metavariables to stand for natural numbers
 with the indicated intended interpretations:
   y: year (two or four digits)
   m: month (0-11, not 1-12)
   d: day of the month (1-31)
   h: hours (0-23)
   mi: minutes (0-59)
   s: seconds (0-59)
   ms: milliseconds (0-999)
See the text (Fig. 12.8, pp. 417-419) for a list of the date methods.

The constructor Date can take different argument patterns:
  new Date( ms ) gives a date ms milliseconds after Jan. 1, 1970.
      new Date( 100000000000 ) gives the date
         Sat Mar 3 04:46:40 EST 1973
      (Milliseconds aren’t displayed.)
  new Date( y, m, d, h, mi, s, ms )
      new Date( 2001, 0, 25, 13, 30, 0, 0 ) gives
        Thu Jan 25 13:30:00 EST 2001
  Arguments may be omitted on the right, with 0’s as defaults.
      new Date( 2001, 0 ) gives the date
        Mon Jan 1 00:00:00 EST 2001

  new Date( ), where the parentheses may be omitted, gives the
    date of the millisecond when it’s executed.


                                  106
Internet Systems




Where dt is a date object,
         dt.toString( )
    returns a string representing date dt (in the same form as dt is
    output).

Where str is a string representing a date,
         Date.parse( str )
    returns the date represented by the string.

   Some forms allowed for the string argument:
       m-d-y − where m and d may be one- or two-digit
       m/d/y − and y may be two- or four-digit.
   The string may also have the same form as that in which dates
     are output.
        The prefix giving the day of the week is ignored and may be
          omitted.
        The month is two or more letters long.
        Every unit after the minutes may be omitted (and defaults to 0).




                                      107
Internet Systems




Example:

<script type = "text/javascript">

    var d = new Date( 100000000000 );
    document.writeln( d );

    d = new Date( 2001, 0, 25, 13, 30, 0, 0 );
    document.writeln("<br>" + d );

    d = new Date( 2001, 0 );
    document.writeln("<br>" + d );

    d = new Date( );
    document.writeln("<br>" + d );

    d = Date.parse( "01-23-2001" );
    document.writeln("<br>" + d );

    d = new Date( Date.parse( "01/23/2001" ) );
    document.writeln("<br>" + d );

    d = new Date( Date.parse( "2-9-01" ) );
    document.writeln("<br>" + d );

    d = new Date( Date.parse(
                   "February 9 15:30 2001" ))
    document.writeln("<br>" + d );

    document.writeln("<br><br>" + d.toString( ) );

    d = new Date( Date.parse( d.toString( ) ) );
    document.writeln("<br><br>" + d );

</script>




                           108
Internet Systems




   Sat Mar 3 04:46:40 EST 1973
   Thu Jan 25 13:30:00 EST 2001
   Mon Jan 1 00:00:00 EST 2001
   Sun Jan 21 13:06:28 EST 2001
   980226000000
   Tue Jan 23 00:00:00 EST 2001
   Sat Feb 9 00:00:00 EST 1901
   Fri Feb 9 15:30:00 EST 2001


   Fri Feb 9 15:30:00 EST 2001


   Fri Feb 9 15:30:00 EST 2001




                                 109
Internet Systems




Most of the date methods have two versions:
  • one based on your computer’s local time zone, and
  • one based on World Time Standard’s Universal Coordinate
    Time (UTC, formerly GMT).

   For example, if dt is a date,
    dt.getDate( ) gives the day of the month (1-31) in local time,
    dt.getUTCDate( ) gives the day of the month in UTC.

   Generally, for get and set methods, the UTC version differs
     from the local-time version by adding “UTC” immediately
     after the “get” or “set”.

The following, where dt is a date object, is a list of most of the
  local-time set methods.
   In all cases, arguments may be omitted on the right, with 0’s as
      defaults.
    dt.setFullYear( y, m, d )
    dt.setMonth( m, d )
    dt.setDate( d )
    dt.setHours( h, mi, s, ms )
    dt.setMinutes( mi, s, ms )
    dt.setSeconds( s, ms )
    dt.setMilliseconds( ms )




                                   110
Internet Systems




The following, where again dt is a date object, is a list of most of
  the local-time get methods.
   dt.getFullYear( ) returns the four-digit year.
   dt.getMonth( ) returns the month (0-11).
   dt.getDate( ) returns the day of the month (1-31).
   dt.getHours( ) returns the hour of the day (0-23).
   dt.getMinutes( ) returns the minute of the hour (0-59).
   dt.getSeconds( ) returns the second of the minute (0-59).
   dt.getMillieconds( ) returns the millisecond of the
                second (0-999).
   dt.getDay( ) returns the day of the week (0-6), 0 being
                Sunday.




                                111
Internet Systems




Example:
<script type = "text/javascript">
    var        d = new Date( );
    d.setFullYear( 2001, 2, 12 );
    d.setHours( 15, 24, 30, 0 );
    document.writeln( d );
    document.writeln("<br><br>" + d.getFullYear( ) );
    document.writeln("<br>" + d.getMonth( ) );
    document.writeln("<br>" + d.getDate( ) );
    document.writeln("<br>" + d.getHours( ) );
    document.writeln("<br>" + d.getMinutes( ) );
    document.writeln("<br>" + d.getSeconds( ) );
    document.writeln("<br>" + d.getMilliseconds( ) );
    document.writeln("<br><br>" + d.getDay( ) );
    document.writeln("<br><br>" + d.toString( ) );
</script>


   Mon Mar 12 15:24:30 EST 2001

   2001
   2
   12
   15
   24
   30
   0

   1

   Mon Mar 12 15:24:30 EST 2001




                                  112
Internet Systems




Boolean and Number Objects
The Boolean and Number objects are wrappers for boolean and
  numeric values.

When a boolean (resp., numeric) value is required, JavaScript
 automatically creates a boolean (resp., numeric) object to store
 the value.

A Boolean object is created explicitly with
     new Boolean( booleanValue )
  where the new object contains
    • value false if booleanValue is one of
        false, 0, null, Number.NaN, or “ “, and
    • value true otherwise.

A Number object is created explicitly with
    new Number( numericValue )

Methods of Boolean and Number
  Let bool be a boolean object and num a number object.
    bool.toString( ) returns “true” (resp., “false”) if
                 the value of bool is true (resp., false).
    num.toString( radix ) returns the string representation of
                 num’s value in radix radix.
    bool.valueOf( ) returns true (resp., false) if the value
                 of bool is true (resp., false).
    num.valueOf( ) returns num‘s (numeric) value.




                               113
Internet Systems




Number constants
    (These are properties of Number, not of its instances.)
   Number.MAX_VALUE             is the largest value that can be
                              represented.
   Number.MIN_VALUE is the smallest positive value that can
                    be represented.
   Number.POSITIVE_INFINITY indicates a value greater
                    than Number.MAX_VALUE.
   Number.NEGATIVE_INFINITY indicates a value less than
                    - Number.MAX_VALUE.
   Number.NaN represents not a number, the value returned by
           an arithmetic expression or a numerical-value
           function invocation that does not result in a number.

Function isNaN( arg ) returns true iff arg is NaN.




                                  114

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:38
posted:3/15/2010
language:English
pages:17