Sunteți pe pagina 1din 31

Java Script

(Functions, Arrays &


Objects)
Event Handler
• An event handler is an attribute
added to an
element that specifies a program to be
run in
response to an event
Ex:
OnClick,OnChange,OnMouseuUp,
OnMouseDown,OnLoad……
Functions
 Enables modularization
 Makes code reusable
 Reduce size and complexity of code
 Efficiency by avoiding repetition
Limits details needed to be
remembered
 Ensures consistency
Modifications are only made
once
Cont..
A module of code that performs a
specific task
Types of functions
• Pre-defined in JavaScript
• User-defined
Functions may:
• Accept data
• Return a value
• Do something else
• Or any combination of the three
Defining Functions
• Format of a function definition
function function-name( parameter-list )
{
declarations and statements
}

– Function name any valid identifier


– Parameter list names of variables that will receive arguments
• Must have same number as function call
• May be empty
– Declarations and statements
• Function body (“block” of code)

... ...and later we use it


variable = FunctionName (arguments);
Cont..
• Returning control
– return statement
– Can return either nothing, or a value
– return expression;
– No return statement same as return;
– Not returning a value when expected is an error
Global Functions
• Global object
– Always available
– Provides 7 methods
– Do not need to explicitly reference Global before method call
– Also holds all global variables, user defined functions
Cont..
Global function Description
escape This function takes a string argument and returns a
string in which all spaces, punctuation, accent
characters and any other character that is not in the
ASCII character set (see Appendix D, ASCII
Character Set) are encoded in a hexadecimal format
(see Appendix E, Number Systems) that can be
represented on all platforms.
eval This function takes a string argument representing
JavaScript code to execute. The JavaScript
interpreter evaluates the code and executes it when
the eval function is called. This function allows
JavaScript code to be stored as strings and executed
dynamically.
isFinite This function takes a numeric argument and returns
true if the value of the argument is not NaN,
Number.POSITIVE_INFINITY or
Number.NEGATIVE_INFINITY; otherwise, the
function returns false.
isNaN This function takes a numeric argument and returns
true if the value of the argument is not a number;
otherwise, it returns false. The function is
commonly used with the return value of parseInt
or parseFloat to determine whether the result is a
proper numeric value.
Fig. 10.9 JavaScript global functions.
Cont…
Global function Description
parseFloat This function takes a string argument and attempts to
convert the beginning of the string into a floating-point
value. If the conversion is unsuccessful, the function
returns NaN; otherwise, it returns the converted value
(e.g., parseFloat( "abc123.45" ) returns NaN,
and parseFloat( "123.45abc" ) returns the value
123.45).
parseInt This function takes a string argument and attempts to
convert the beginning of the string into an integer value. If
the conversion is unsuccessful, the function returns NaN;
otherwise, it returns the converted value (e.g.,
parseInt( "abc123" ) returns NaN, and
parseInt( "123abc" ) returns the integer value
123). This function takes an optional second argument,
from 2 to 36, specifying the radix (or base) of the
number. Base 2 indicates that the first argument string is
in binary format, base 8 indicates that the first argument
string is in octal format and base 16 indicates that the first
argument string is in hexadecimal format. See see
Appendex E, Number Systems, for more information on
binary, octal and hexadecimal numbers.

unescape This function takes a string as its argument and returns a


string in which all characters previously encoded with
escape are decoded.
Recursion
• Recursive functions
– Call themselves
• Recursion step or recursive call
• Part of return statement
– Must have base case
• Simplest case of problem
• Returns value rather than calling itself
– Each recursive call simplifies input
• When simplified to base case, functions return
Recursion vs. Iteration
• Iteration
– Explicitly uses repetition structures to achieve result
– Terminates when loop-continuation condition fails
– Often faster than recursion
• Recursion
– Repeats through function calls
– Terminates when base case reached
– Slower due to function call overhead
• Each call generates new copy of local variables
– Easy to read and debug when modeling problem with naturally
recursive solution
Arrays
• An array is a group of memory location that all
have the same name and multiple data type.
• An Array is an enumerated list of variables. It's a
programming construct that allows programmers to
replace this…
x0=0;
x1=1;
x2=“MASTER”;
x3=3.5;
…with this…
x[0]=0;
x[1]=1;
x[2]=“MASTER”;
x[3]=3.5;
• The index (the number in the brackets [] )can be
referenced by a variable, allowing for easy looping
through the data structure.
The ‘new’
This is the DECLARATION
operator & Pair of
identifier of creates an
the new ALLOCATION
instance
paren-
theses
instance
Declaration…stmt

student = new Array( 4 )


The
‘assignment’
operator Length of
This is the parent object
the new
(or class) of the new
instance of
instance
13
Cont…

var myArray = ['January', 'February',


'March'];
or
var myArray = new Array('January',
'February', 'March')
Passing Arrays to Function
• Two methods
Pass by Value
Pass by Reference
“with pass by value , changes to the copy of the
called function do not affect the original
variable’s value in the calling function”.
Ex: var myArray=new Array[10,20,30];
Myfunction(myArray[0]);
Cont…
• “with pass by reference , changes to the copy of
the called function affect the original variable’s
value in the calling function”.
Ex: var myArray=new Array[10,20,30];
Myfunction(myArray);
Methods
• Array.join(delimeter)
• to create a string containing all the element in the
Array

• Array.sort([function])
• The sort() method, by default, will sort an Array
alphabetically. If you would like to create your own
sorting criteria, supply a function for the sort method
to call. Sort will pass your function (a,b).

• Array.reverse()
• Reverses the order of the elements
Multidimensional Array
• Multidimensional arrays with subscripts often are
used to represent tables of values consisting of
information Arranged in rows and columns

Co lumn 0 Co lumn 1 Co lumn 2 Co lumn 3

Ro w 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Ro w 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Ro w 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column sub scrip t (o r index)

Ro w subscrip t (or inde x)

Arra y na me
Cont…
• Javascript does not support directly
• Allow programmer to spwcify as One dimentional
Array
Arrays of 1D array
var b=[[1,2],[3,4]]
2D Array with rows of different length
var b=[[1,2],[,3,5]]
Objects
• Not Object Oriented – but Object-Based
• No class,No ploymorphism,No inheritance
etc..
• collections of properties and methods
Properties:
objectName.property
eg. document.bgColor; returns the background color of
the document.
Methods:
objectName.methodName()
eg. document.write(“Some text”); writes into the
document.
Math Object
• It is not possible to use the math Object as
constructor with the new operator.
• Allow the programmer to perform many common
mathematical calculations
Eg: document.write(Math.sqrt(900.0));
Method
abs()
Celi()
Floor()
Exp()
Log()
Pow()
……
……
String Object
• JavaScript’s string and character-processing capabilities
• Appropriate for processing names, addresses, credit card
information, etc.
Methods
 charAt
Returns the character at specific position
 charCodeAt
Returns Unicode value of the character at specific position
 fromCharCode
Returns string created from series of Unicode values
 toLowerCase
Returns lowercase version of string
 toUpperCase
Returns uppercase version of string
 indexOf and lastIndexOf
Search for a specified substring in a string
Date Object
• Provides methods for date and time
manipulations
• Indicates a particular instance of
Time(It measured in millisecound
since 1 jan 1970)
• Constructor
new Date();
new Date(year,month,date,hr,min,sec,ms)
Date Object
Method Description

getDate() Returns a number from 1 to 31 representing the day of the month in local time or UTC, respectively.
getUTCDate()
getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC,
respectively.
getUTCDay()
getFullYear() Returns the year as a four-digit number in local time or UTC, respectively.
getUTCFullYear()
getHours() Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.
getUTCHours()
getMilliseconds() Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively.
The time is stored in hours, minutes, seconds and milliseconds.
getUTCMilliSeconds()

getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.
getUTCMinutes()
getMonth() Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC,
respectively.
getUTCMonth()
getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.
getUTCSeconds()
getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object.

getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTC—previously
known as Greenwich Mean Time (GMT).

setDate( val )
Sets the day of the month (1 to 31) in local time or UTC, respectively.

setUTCDate( val )
Fig. 12.8 Methods of the Date object.

24
Cont…
Method Description

setFullYear( y, m, d )
Sets the year in local time or UTC, respectively. The second and third
arguments representing the month and the date are optional. If an optional
setUTCFullYear( y, m, d ) argument is not specified, the current value in the Date object is used.

setHours( h, m, s, ms )
Sets the hour in local time or UTC, respectively. The second, third and fourth
arguments representing the minutes, seconds and milliseconds are optional. If
setUTCHours( h, m, s, ms ) an optional argument is not specified, the current value in the Date object is
used.

setMilliSeconds( ms )
Sets the number of milliseconds in local time or UTC, respectively.

setUTCMilliseconds( ms )
setMinutes( m, s, ms )
Sets the minute in local time or UTC, respectively. The second and third
arguments representing the seconds and milliseconds are optional. If an
setUTCMinutes( m, s, ms ) optional argument is not specified, the current value in the Date object is
used.

setMonth( m, d )
Sets the month in local time or UTC, respectively. The second argument
representing the date is optional. If the optional argument is not specified, the
setUTCMonth( m, d ) current date value in the Date object is used.

setSeconds( s, ms )
Sets the second in local time or UTC, respectively. The second argument
representing the milliseconds is optional. If this argument is not specified, the
setUTCSeconds( s, ms ) current millisecond value in the Date object is used.

Fig. 12.8 Methods of the Date object.


25
Cont…
Method Description

setTime( ms )
Sets the time based on its argument—the number of elapsed milliseconds
since January 1, 1970.

toLocaleString() Returns a string representation of the date and time in a form specific to the
computer’s locale. For example, September 13, 2001 at 3:42:22 PM is
represented as 09/13/01 15:47:22 in the United States and 13/09/01
15:47:22 in Europe.

toUTCString() Returns a string representation of the date and time in the form: 19 Sep
2001 15:47:22 UTC

toString() Returns a string representation of the date and time in a form specific to the
locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United
States).

valueOf() The time in number of milliseconds since midnight, January 1, 1970.

Fig. 12.8 Methods of the Date object.

26
window Object
• Provides methods for manipulating
browser window
Method or Property Description
open( url, name, options ) Creates a new window with the URL of the window set to
url, the name set to name, and the visible features set by
the string passed in as option.
prompt( prompt, default ) Displays a dialog box asking the user for input. The text of
the dialog is prompt, and the default value is set to default.
close() Closes the current window and deletes its object from
memory.
window.focus() This method gives focus to the window (i.e., puts the
window in the foreground, on top of any other open
browser windows).
window.document This property contains the document object representing
the document currently inside the window.
window.closed This property contains a boolean value that is set to true if
the window is closed, and false if it is not.
window.opener This property contains the window object of the window
27
that opened the current window, if such a window exists.
Document Object
• Manipulate document that is
currently visible in the browser
window
Method or Property Description
write( string ) Writes the string to the XHTML document as
XHTML code.
writeln( string ) Writes the string to the XHTML document as
XHTML code and adds a newline character at
the end.
document.cookie This property is a string containing the values
of all the cookies stored on the user’s computer
for the current document. See Section 12.9,
Using Cookies.
document.lastModified This property is the date and time that this
document was last modified.
Fig. 12.12 Important document object methods and properties.
28
Using Cookies
• Cookie
– Data stored on user’s computer to maintain
information about client during and
between browser sessions
– Can be accessed through cookie property
– Set expiration date through expires
property
– Use escape function to convert non-
alphanumeric characters to hexadecimal
escape sequences
– unescape function converts hexadecimal
29
escape sequences back to English
Using Cookies
• JavaScript provides some limited, persistent
storage, called cookies:
– Data is stored in a text file on the client
– name=value
–Multiple values are delimited by a
semicolon
• JavaScript has a property of the document
object named cookie, document.cookie
• A cookie can be removed from cookie.txt either
because it expires or because the cookie file
gets too large
• There are limits (generally):-Up to 300 cookies
per browser, 20 cookies per web server, and 4
KB of data per cookie
30
Thank you

31

S-ar putea să vă placă și