0% found this document useful (0 votes)
42 views30 pages

Pertemuan 8

Uploaded by

lulanc
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views30 pages

Pertemuan 8

Uploaded by

lulanc
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 30

Matakuliah : M0114/Web Based Programming

Tahun : 2005
Versi :5

Session 8
JavaScript/Jscript: Objects
Learning Outcomes

Pada akhir pertemuan ini, diharapkan mahasiswa


akan mampu :
• menghasilkan web page dengan menerapkan
struktur data Array dan konsep Object (C3)
Outline Materi

8.1 Introduction
8.2 Thinking About Objects
8.3 Math Object
8.4 String Object
8.4.1 Fundamentals of Characters and Strings
8.4.2 Methods of the String Object
8.4.3 Character Processing Methods
8.4.4 Searching Method
8.4.5 Splitting Strings and Obtaining Substrings
8.4.6 HTML Markup Methods
8.5 Date Object
8.6 Boolean and Number Objects
8.1 Introduction

• Up till now
– JavaScript used to illustrate basic programming
concepts
• JavaScript can also
– Manipulate every element of an HTML document
from a script
• In this chapter
– Provide more formal treatment of objects
– Overview and serve as reference for
• Several of JavaScript’s built-in objects
• Demonstrates their capabilities
8.2 Thinking About Objects

• JavaScript - object-based programming


language
• Objects
– Two categories
• Animate
• Inanimate
– Attributes
– Behaviors
– Encapsulate data and methods
– Property: Information hiding
– Communicate with programs through interfaces
• Most future software will be built by
combining objects
continue..
8.2 Thinking About Objects

• JavaScript uses objects to


– Interact with elements (or objects) of an HTML
document
• window object
– Enables script to manipulate browser window
– window.status
– window.alert
• document object
– Provides access to every element of an HTML
document
– Encapsulate various capabilities in a script
• array object
• Enables script to manipulate a collection of data
8.3 Math Object
• Math object’s methods
– Allow programmer to perform many common mathematical
calculations
Properties of the Math object
C o n sta n t De sc rip tio n Va lu e
Math.E Euler’s constant. Approximately 2.718.
Math.LN2 Natural logarithm of 2. Approximately 0.693.
Math.LN10 Natural logarithm of 10. Approximately 2.302.
Math.LOG2E Base 2 logarithm of Approximately 1.442.
Euler’s constant.
Math.LOG10E Base 10 logarithm of Approximately 0.434.
Euler’s constant.
Math.PI PI - ratio of circle’s Approximately
circumference to its 3.141592653589793.
diameter.
Math.SQRT1_2 Square root of 0.5. Approximately 0.707.
Math.SQRT2 Square root of 2.0. Approximately 1.414.

© Copyright 2001 by Deitel & Associates. All Rights Reserved continue..


8.3 Math Object

Commonly Used Math Object Methods


Me tho d De sc rip tio n Exa m p le
abs( x ) absolute value of x abs( -3.67 ) is 3.67
ceil( x ) rounds x to the next highest integer ceil( 9.2 ) is 10.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
floor( x ) rounds x to the next lowest integer floor( -9.8 ) is -10.0
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
min( x, y ) smaller value of x and y min( 2.3, 12.7 ) is 2.3
min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to power y (xy) pow( 2.0, 7.0 ) is 128.0
pow( 9.0, .5 ) is 3.0

continue..
© Copyright 2001 by Deitel & Associates. All Rights Reserved
8.3 Math Object

• Commonly used Math object methods


– Continued from previous slide
Me tho d De sc rip tio n Exa m p le
round( x ) rounds x to the closest integer round( 9.75 ) is 10
round( 9.25 ) is 9
sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0.0
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x (x in tan( 0.0 ) is 0.0
radians)

© Copyright 2001 by Deitel & Associates. All Rights Reserved


8.4 String Object

• String Object
– JavaScript’s string and character processing
capabilities
• Appropriate for developing
– Text editors
– Word processors
– Page layout software
– Computerized typesetting systems
– Other kinds of text-processing software
8.4.1 Fundamentals of Characters and
Strings
• Characters
– Fundamental building blocks of JavaScript
programs
• String
– Series of Characters treated as a single unit
– May include
• Letters
• Digits
• Special Characters
+, _, /, $, etc.

continue..
8.4.1 Fundamentals of Characters and
Strings

• String literals / string constant


– Written as sequence of characters in single or
double quotation marks
• Strings may be assigned to variables in
declarations
var color = “blue”;
• Strings may be compared with
– Relational operators
– Equality operators
8.4.2 Methods of the String Object

• String object
– Encapsulates the attributes and behaviors of a string
of characters
• Format for calling methods (except in certain
cases)
stringName.methodName( );
• Provides methods for
– Selecting characters from a string
– Combining strings (concatenation)
– Obtaining substrings of a string
– Searching for substrings within a string
– Tokenizing a string
– Converting strings to all uppercase or lowercase
– Generate HTML tags
continue..
8.4.2 Methods of the String Object
Me th o d De sc rip tio n
charAt( index ) Returns the character at the specified index. If there is no
character at that index, charAt returns an empty string. The
first character is located at index 0.
charCodeAt( index ) Returns the Unicode value of the character at the specified index.
If there is no character at that index, charCodeAt returns NaN.
concat( string ) Concatenates its argument to the end of the string that invokes
the method. This method is the same as adding two strings with
the string concatenation operator + (e.g., s1.concat( s2 ) is
the same as s1 + s2). The original strings are not modified.
fromCharCode( value1, Converts a list of Unicode values into a string containing the
value2, … ) corresponding characters.
indexOf(substring, Searches for the first occurrence of substring starting from
index ) position index in the string that invokes the method. The method
returns the starting index of substring in the source string (-1 if
substring is not found). If the index argument is not provided, the
method begins searching from index 0 in the source string.
lastIndexOf( substring, Searches for the last occurrence of substring starting from
index ) position index and searching toward the beginning of the string.
The method returns the starting index of substring in the source
string (-1 if substring is not found). If index is not provided, the
method begins searching from end of the source string.
© Copyright 2001 by Deitel & Associates. All Rights Reserved continue..
8.4.2 Methods of the String Object
Me th o d De sc rip tio n
slice( start, Returns a string containing the portion of the string from index start
end ) through index end. If the end index is not specified, the method
returns a string from the start index to the end of the source string. A
negative end index specifies an offset from the end of the string
starting from a position one past the end of the last character (so, -1
indicates the last character position in the string).
split( string ) Splits the source string into an array of strings (tokens) where its
string argument specifies the delimiter (i.e., the characters that
indicate the end of each token in the source string).
substr(start, Returns a string containing length characters starting from index start
length ) in the source string. If length is not specified, a string containing
characters from start to the end of the source string is returned.
substring( Returns a string containing the characters from index start up to but
start, end ) not including index end in the source string.
toLowerCase() Returns a string in which all uppercase letters are converted to
lowercase letters. Non-letter characters are not changed.
toUpperCase() Returns a string in which all lowercase letters are converted to
uppercase letters. Non-letter characters are not changed.
toString() Returns the same string as the source string.
valueOf() Returns the same string as the source string.
© Copyright 2001 by Deitel & Associates. All Rights Reserved
8.4.3 Character Processing Methods

• String object’s character processing


methods
– charAt
• Returns the character at a specific position
– charCodeAt
• Returns the Unicode value of the character at a specific
position
– fromCharCode
• Creates a string from a list of Unicode values
– toLowerCase
• Returns the lowercase version of a string
– toUppercase
Sample P
• Returns the uppercase version of a string rogram
8.4.4 Searching Method

• Often useful to search for character or


sequence of characters in a string
• String object’s searching methods
– Indexof and lastindexof
• Search for a specified substring in a string

Sample Pr
ogram
8.4.5 Splitting Strings and Obtaining
Substrings
• When you read a sentence
– Break it into individual words or tokens
• Process of breaking string into tokens is
tokenization
– Also done by interpreters
• Tokens separated by delimiters
– Typically white-space characters
– Other characters can be used
• Results of tokenization are displayed in
HTML TEXTAREA GUI component

continue..
8.4.5 Splitting Strings and Obtaining
Substrings

• String object’s split method


– Breaks a string into its component tokens
• String object’s substring method
– Returns a portion of a string

Sample Pro
gram
8.4.6 HTML Markup Methods
Me th o d De sc rip tio n
anchor( name ) Wraps source string in anchor element <A></A> with
name as anchor name.
big() Wraps source string in a <BIG></BIG> element.
blink() Wraps source string in a <BLINK></BLINK> element.
bold() Wraps source string in a <B></B> element.
fixed() Wraps source string in a <TT></TT> element.
fontcolor( color ) Wraps source string in a <FONT></FONT> element with
color as the font color.
fontsize( size ) Wraps source string in a <FONT></FONT> element with
size as HTML font size.
italics() Wraps source string in an <I></I> element.
link( url ) Wraps source string in an <A></A> with url as the
hyperlink location.
small() Wraps source string in a <SMALL></SMALL> element.
strike() Wraps source string in a <STRIKE></STRIKE>
element.
sub() Wraps source string in a <SUB></SUB> element.
Sample
sup() Wraps source string in a <SUP></SUP> element. Program
© Copyright 2001 by Deitel & Associates. All Rights Reserved
8.5 Date Object
• JavaScript’s Date object
– Provides methods for date and time manipulation
• Date and time processing can be performed
based on
– Local time zone
– Universal Coordinated Time (UTC) /
Greenwich Mean Time (GMT)
– Most methods in Date object have local time zone
and UTC versions
• When using Date object
– Initialize Date object with current date and time
var current = new Date();
– Allocates memory for object, calls Date object
constructor
• Constructor – initializer method for an object
continue..
8.5 Date Object

• New Date object creation


new Date( year, month, date, hours,
minutes, seconds, milliseconds );
– Hours, minutes, seconds and milliseconds are
optional
– If argument to the right is specified, all arguments to
the left must also be specified
– Month represented internally as integers from 0-11
• Therefore, March is indicated by 2, November by 10,
etc.
• Write out years in 4-digit form (i.e. ‘2000’, not
’00’)
– Avoid potential Y2K problems
continue..
8.5 Date Object
• Two other methods can be called without
creating new Date object
– Both methods return number of milliseconds between
midnight, January 1, 1970 and date specified by
argument
1. Date.parse( argument );
– Argument
• Short dates
– MM-DD-YY, MM-DD-YYYY, MM/DD/YY,
MM/DD/YYYY
• Long dates
– Month (at least first two letters), date and year
– Time in either 12 or 24 hour clocks
– Text and days of the week are ignored
continue..
8.5 Date Object

2. Date.UTC( argument );
– Argument - same for as date construct
( Y, M, D, H, M, S, M )
– Either method can be converted to a Date object
var theDate = new
Date( numberOfMilliseconds );
– numberOfMilliseconds equals the result of Date.UTC
or Date.Parse
• For listing of Date object methods, see Figure
18.8

Sample Pr
ogram
8.6 Boolean and Number Objects

• Boolean and Number objects


– Provided as object wrappers for
• Boolean true/false values
• Numbers
– Wrappers define methods and properties useful in
manipulating boolean values and numbers
• Number object
– JavaScript automatically creates Number objects to
store numeric values
– Programmers can create a Number object with
var n = new Number( numericValue );
– For other Number object methods, see figure 18.11
continue..
8.6 Boolean and Number Objects

• Boolean object
– When boolean value required in a program,
automatically created by JavaScript to store the value
using Boolean object
– Programmers can create Boolean objects explicitly
var b = new Boolean( booleanValue );
– If booleanvalue equals false, 0, null, Number.NaN
or empty string (“ ”)
• Boolean object contains false
– Otherwise
• Boolean Object contains true

continue..
8.6 Boolean and Number Objects

• Methods of Boolean object

Me tho d De sc rip tio n


toString() Returns the string “true” if the value of the Boolean
object is true; otherwise, returns the string “false.”
valueOf() Returns the value true if the Boolean object is true;
otherwise, returns false.

© Copyright 2001 by Deitel & Associates. All Rights Reserved continue..


8.6 Boolean and Number Objects

• Methods of Number object


Me th o d o r p ro p e rty De sc rip tio n
toString( radix ) Returns the string representation of the number. The
optional radix argument (a number from 2 to 36) specifies
the base of the number. For example, radix 2 results in the
binary representation of the number, 8 results in the octal
representation of the number, 10 results in the decimal
representation of the number and 16 results in the
hexadecimal representation of the number. See the
document “Number Systems” on the CD that accompanies
this book for a review of the binary, octal, decimal and
hexadecimal number systems.
valueOf() Returns the numeric value.
Number.MAX_VALUE This property represents the largest value that can be
stored in a JavaScript program—approximately
1.79E+308
Number.MIN_VALUE This property represents the smallest value that can be
stored in a JavaScript program—approximately 2.22E–308

© Copyright 2001 by Deitel & Associates. All Rights Reserved continue..


8.6 Boolean and Number Objects

• Methods of Number object


– Continued from previous slide
Me th o d o r p ro p e rty De sc rip tio n
Number.NaN This property represents not a number—a value returned
from arithmetic expressions that do not result in a number
(e.g., the expression parseInt("hello") cannot
convert the string "hello" into a number, so
parseInt would return Number.NaN). To determine
whether a value is NaN, test the result with function
isNaN which returns true if the value is NaN;
otherwise, it returns false.
Number.NEGATIVE_INFINITY This property represents a value less than
-Number.MAX_VALUE.
Number.POSITIVE_INFINITY This property represents a value greater than
Number.MAX_VALUE.

© Copyright 2001 by Deitel & Associates. All Rights Reserved


End of Session 8

You might also like