COMP284 Scripting Languages
Lecture 16: JavaScript (Part 3)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Functions
Defining a function
Calling a function
Variable-length argument lists
Static variables
Example
Nested function definitions
2 JavaScript libraries
3 (User-defined) Objects
Object Literals
Object Constructors
Definition and use
Prototype property
Public and private static variables
Pre-defined objects
COMP284 Scripting Languages Lecture 16 Slide L16 1
Functions Defining a function
Functions
Function definitions can take several different forms in JavaScript
including:
function identifier ( param1 , param2 , ...) {
statements }
var identifier = fu n c t i on ( param1 , param2 , ...) {
statements }
Such function definitions are best placed in the head section
of a HTML page or in a library that is then imported
Function names are case-sensitive
The function name must be followed by parentheses
A function has zero, one, or more parameters that are variables
Parameters are not typed
identifier.length can be used inside the body of the function to
determine the number of parameters
COMP284 Scripting Languages Lecture 16 Slide L16 2
Functions Defining a function
Functions
Function definitions can take several different forms in JavaScript
including:
function identifier ( param1 , param2 , ...) {
statements }
var identifier = fu n c t i on ( param1 , param2 , ...) {
statements }
The return statement
return value
can be used to terminate the execution of a function and to make
value the return value of the function
The return value does not have to be of a primitive type
A function can contain more than one return statement
Different return statements can return values of different types
; there is no return type for a function
COMP284 Scripting Languages Lecture 16 Slide L16 3
Functions Calling a function
Calling a function
A function is called by using the function name followed by a list of
arguments in parentheses
function identifier ( param1 , param2 , ...) {
...
}
... identifier ( arg1 , arg2 ,...) ... // Function call
The list of arguments can be shorter as well as longer as
the list of parameters
If it is shorter, then any parameter without corresponding argument
will have value undefined
function sum ( num1 , num2 ) { return num1 + num2 }
sum1 = sum (5 ,4) // sum1 = 9
sum2 = sum (5 ,4 ,3) // sum2 = 9
sum3 = sum (5) // sum3 = NaN
COMP284 Scripting Languages Lecture 16 Slide L16 4
Functions Calling a function
‘Default values’ for parameters
JavaScript does not allow to specify default values for function
parameters
Instead a function has to check whether a parameter has the value
undefined and take appropriate action
function sum ( num1 , num2 ) {
if ( num1 == un d e f ined ) num1 = 0
if ( num2 == un d e f ined ) num2 = 0
return num1 + num2
}
sum3 = sum (5) // sum3 = 5
sum4 = sum () // sum4 = 0
COMP284 Scripting Languages Lecture 16 Slide L16 5
Functions Variable-length argument lists
Variable-length argument lists
Every JavaScript function has a property called arguments
The arguments property consists of an array of all the arguments
passed to a function
As for any JavaScript array, arguments.length can be used to
determine the number of arguments
// Function that returns the sum of all its argu m e n t s
function sumA ll () { // no minimum number of ar g u m e nts
var sum = 0
for ( var i =0; i < arguments . length ; i ++)
sum = sum + a r g u ments [ i ]
return sum
}
sum0 = sumAll () // sum0 = 0
sum1 = sumAll (5) // sum1 = 5
sum2 = sumAll (5 ,4) // sum2 = 9
sum3 = sumAll (5 ,4 ,3) // sum3 = 12
COMP284 Scripting Languages Lecture 16 Slide L16 6
Functions Static variables
JavaScript functions and Static variables
JavaScript does not have a static keyword to declare a variable to be
static and preserve its value between different calls of a function
The solution is to use a function property instead
function counter () {
counter . count = counter . count || 0 // function property
counter . count ++
return counter . count
}
document . writel n (" 1: sta tic count = "+ counter ())
document . writel n (" 2: sta tic count = "+ counter ())
document . writel n (" 3: glo bal counter . count = "+ counter . count )
1: st atic count = 1
2: st atic count = 2
3: gl obal counter . count = 2
As the example shows the function property is global/public
Private static variables require more coding effort
COMP284 Scripting Languages Lecture 16 Slide L16 7
Functions Example
JavaScript functions: Example
function bubble_ s o rt ( array ) {
if (!( array && array . c onstructor == Array ))
throw (" Argument not an array ")
for ( var i =0; i < array . length ; i ++) {
for ( var j =0; j < array . length -i ; j ++) {
if ( array [j +1] < array [j ]) {
// swap can c hange array because array is
// pa ssed by refer e n c e
swap ( array , j , j +1)
} } }
return array
}
function swap ( array , i , j) {
var tmp = array [i ]
array [i] = array [j ]
array [j] = tmp
}
COMP284 Scripting Languages Lecture 16 Slide L16 8
Functions Example
JavaScript functions: Example
function bubble_ s o rt ( array ) { ... }
function swap ( array , i , j) { ... }
array = [2 ,4 ,3 ,9 ,6 ,8 ,5 ,1]
document . writel n (" array before sorting "+
array . join ( " , " )+ " <br >" )
array b efore sorting 2, 4, 3 , 9 , 6, 8 , 5, 1 <br >
sorted = b ubble_sort ( array . slice (0)) // slice creates copy
document . writel n (" array after sorting of copy "+
array . join ( " , " )+ " < br >" )
array after sorting of copy 2, 4 , 3 , 9, 6 , 8, 5 , 1 <br >
sorted = b ubble_sort ( array )
document . writel n (" array after sorting of itself " +
array . join ( " , " )+ " <br >" )
array after sorting of itself 1, 2 , 3, 4 , 5, 6 , 8, 9 <br >
document . writel n (" sorted array "+
sorted . join ( " , " )+ " <br > ")
sorted array 1, 2 , 3, 4 , 5, 6 , 8, 9 <br >
COMP284 Scripting Languages Lecture 16 Slide L16 9
Functions Nested function definitions
Nested function definitions
Function definitions can be nested in JavaScript
Inner functions have access to the variables of outer functions
By default, inner functions can not be invoked from outside
the function they are defined in
function bubble_ s o rt ( array ) {
function swap (i , j) {
// swap can c hange array because array is
// a local variable of the outer function bubble_so r t
var tmp = array [ i ]; array [i ] = array [ j ]; array [j ] = tmp ;
}
if (!( array && array . c onstructor == Array ))
throw (" Argument not an array ")
for ( var i =0; i < array . length ; i ++) {
for ( var j =0; j < array . length -i ; j ++) {
if ( array [j +1] < array [j ]) swap (j, j +1)
} }
return array }
COMP284 Scripting Languages Lecture 16 Slide L16 10
JavaScript libraries
JavaScript libraries
Collections of JavaScript functions (and other code), libraries, can be
stored in one or more files and then be reused
By convention, files containing a JavaScript library are given the file
name extension .js
<script>-tags are not allowed to occur in the file
A JavaScript library is imported using
< scri pt src = " url " > </ script >
where url is the (relative or absolute) URL for library
< scri pt src = " http : // student . csc . liv . ac . uk /
sguh / jsLib . js " >
</ script >
One such import statement is required for each library
Import statements are typically placed in the head section of a page or
at the end of the body section
Web browers typically cache libraries
COMP284 Scripting Languages Lecture 16 Slide L16 11
JavaScript libraries
JavaScript libraries: Example
~ullrich/public_html/sort.js
function bubble_ s o rt ( array ) {
... swap ( array , j , j +1) ...
return array
}
function swap ( array , i , j) { ... }
example.html
<! DOCTYPE html >
< html lang = ' en - GB ' >< head > < title > Sorting example </ title >
< scri pt src = " http :// student . csc . liv . ac . uk /
ullrich / sort .js ">
</ script > </ head >
<body >
< scri pt type = " text / javascript " >
array = [2 ,4 ,3 ,9 ,6 ,8 ,5 ,1];
sorted = b ubble_sort ( array . slice (0))
</ script >
</ body > </ html >
COMP284 Scripting Languages Lecture 16 Slide L16 12
(User-defined) Objects Object Literals
Object Literals
JavaScript is an object-oriented language, but one without classes
Instead of defining a class,
we can simply state an object literal
{ property1 : value1 , prope rty2 : value2 , ... }
where property1, property2, . . . are variable names
and value1, value2, . . . are values (expressions)
var per son1 = {
age : (30 + 2),
gender : ' male ' ,
name : { first : ' Bob ' , last : ' Smith ' } ,
inte rests : [ ' music ' , ' skiing ' ],
he llo : fun ction () { return ' Hi ! I \ ' m ' + this . name . first + ' . ' }
};
per son1 . age --> 32 // dot n otati o n
per son1 [ ' gender ' ] --> ' male ' // bra cket nota tion
per son1 . name . first --> ' Bob '
per son1 [ ' name ' ][ ' last ' ] --> ' Smith '
COMP284 Scripting Languages Lecture 16 Slide L16 13
(User-defined) Objects Object Literals
Object Literals
var per son1 = {
...
name : { first : ' Bob ' , last : ' Smith ' } ,
he llo : fun ction () { return ' Hi ! I \ ' m ' + this . name . first + ' . ' }
};
per son1 . hell o () --> "Hi ! I ' m Bob ."
Every part of a JavaScript program is executed in a particular
execution context
Every execution context offers a keyword this as a way of referring to
itself
In person1.hello() the execution context of hello() is person1
; this.name.first is person1.name.first
COMP284 Scripting Languages Lecture 16 Slide L16 14
(User-defined) Objects Object Literals
Object Literals
var per son1 = {
name : { first : ' Bob ' , last : ' Smith ' } ,
gr eet : fun ction () { return ' Hi ! I \ ' m ' + name . first + ' . ' } ,
fu ll1 : this . name . firs t + " " + this . name . last ,
fu ll2 : name . first + " " + name . last
};
per son1 . gree t () --> "Hi ! I ' m u n defin e d . "
per son1 . full 1 --> " undefi ned unde f ined "
per son1 . full 2 --> " undefi ned unde f ined "
In person1.greet() the execution context of greet() is person1
; but name.first does not refer to person1.name.first
In the (construction of the) object literal itself, this does not refer to
person1 but its execution context (the window object)
; none of name.first, name.last, this.name.first, and
this.name.last refers to properties of this object literal
COMP284 Scripting Languages Lecture 16 Slide L16 15
(User-defined) Objects Object Constructors
Objects Constructors
JavaScript is an object-oriented language, but one without classes
Instead of defining a class,
we can define a function that acts as object constructor
variables declared inside the function will be instance variables of the object
; each object will have its own copy of these variables
it is possible to make such variables private or public
inner functions will be methods of the object
it is possible to make such functions/methods private or public
private variables/methods can only be accessed inside the function
public variables/methods can be accessed outside the function
Whenever an object constructor is called,
prefixed with the keyword new, then
a new object is created
the function is executed with the keyword this bound to that object
COMP284 Scripting Languages Lecture 16 Slide L16 16
(User-defined) Objects Definition and use
Objects: Definition and use
fu nc tion S om eO bj () {
in st Var2 = ' B ' // pr iv at e variab le
var in stVar3 = ' C ' // pr iv at e variab le
this . in st Var1 = ' A ' // publi c va ri ab le
this . me th od 1 = function () { // public method
// use of a public variable , e.g . ` in st Var1 ' , must be pr ec ed ed by ` th is '
return ' m1[ ' + this . instV ar 1 + ' ] ' + m et ho d3 () }
this . me th od 2 = function () { // public method
// call s of a public method , e.g . ` me th od 1 ' , must be prec ed ed by ` this '
return ' m2 [ ' + this . met ho d1 () + ' ] ' }
me th od 3 = fu nction () { // pr iv at e method
return ' m3 [ ' + i ns tVar2 + ' ] ' + method4 () }
var me th od 4 = function () { // p ri va te method
return ' m4 [ ' + i ns tVar3 + ' ] ' }
}
obj = new So me Ob j () // cre at es a new object
obj . ins tV ar 1 --> "A " | obj . method2 () --> " m2 [m1 [A] m3 [ B] m4 [ C ]] "
obj . ins tV ar 2 --> u nd efine d | obj . m et ho d3 () --> erro r
obj . ins tV ar 3 --> u nd efine d | obj . m et ho d4 () --> erro r
| obj . method1 () --> " m1 [A ] m3[B ] m4[C ] "
COMP284 Scripting Languages Lecture 16 Slide L16 17
(User-defined) Objects Definition and use
Objects: Definition and use
function SomeObj () {
this . instVar1 = 'A' // pu blic variable
instVar2 = ' B ' // p rivate variable
var instVar3 = ' C ' // private variable
this . method1 = function () { ... } // p ublic method
this . method2 = function () { ... } // p ublic method
method3 = function () { ... } // private method
var method 4 = f u n c t i o n () { ... } // private method
}
Note that all of instVar1 to instVar3, method1 to method4 are
instance variables (properties, members) of someObj
The only difference is that instVar1 to instVar3 store strings
while method1 to method4 store functions
; every object stores its own copy of the methods
COMP284 Scripting Languages Lecture 16 Slide L16 18
(User-defined) Objects Prototype property
Objects: Prototype property
All functions have a prototype property that can hold
shared object properties and methods
; objects do not store their own copies of these properties and
methods but only store references to a single copy
function SomeObj () {
this . instVar1 = 'A' // pu blic variable
instVar2 = ' B ' // p rivate variable
var instVar3 = ' C ' // private variable
SomeObj . p r o t otype . m e thod1 = fu n c t i o n () { ... } // pu blic
SomeObj . p r o t otype . m e thod2 = fu n c t i o n () { ... } // pu blic
method3 = function () { ... } // private method
var method 4 = f u n c t i o n () { ... } // private method
}
Note: prototype properties and methods are always public!
COMP284 Scripting Languages Lecture 16 Slide L16 19
(User-defined) Objects Prototype property
Objects: Prototype property
The prototype property can be modified ‘on-the-fly’
; all already existing objects gain new properties / methods
; manipulation of properties / methods associated with the
prototype property needs to be done with care
fu nctio n Som eObj () { ... }
obj1 = new Som eO bj ()
obj2 = new Som eO bj ()
do cumen t . wri teln ( obj1 . ins tV ar4 ) // un def ined
do cumen t . wri teln ( obj2 . ins tV ar4 ) // un def ined
So meObj . prot oty pe . in stVar 4 = ' A '
do cumen t . wri teln ( obj1 . ins tV ar4 ) // ' A '
do cumen t . wri teln ( obj2 . ins tV ar4 ) // ' A '
So meObj . prot oty pe . in stVar 4 = ' B '
do cumen t . wri teln ( obj1 . ins tV ar4 ) // ' B '
do cumen t . wri teln ( obj2 . ins tV ar4 ) // ' B '
obj1 . ins tVar4 = ' C' // cre at es a new in sta nc e v ariab le for obj1
So meObj . prot oty pe . in stVar 4 = ' D '
do cumen t . wri teln ( obj1 . ins tV ar4 ) // ' C ' !!
do cumen t . wri teln ( obj2 . ins tV ar4 ) // ' D ' !!
COMP284 Scripting Languages Lecture 16 Slide L16 20
(User-defined) Objects Prototype property
Objects: Prototype property
The prototype property can be modified ‘on-the-fly’
; all already existing objects gain new properties / methods
; manipulation of properties / methods associated with the
prototype property needs to be done with care
fun ction SomeObj () { ... }
obj1 = new S omeO bj ()
obj2 = new S omeO bj ()
Som eObj . pr o totype . i nstVar 5 = ' E '
Som eObj . pr o totype . se t InstVar 5 = funct ion ( arg ) {
this . i nstVar 5 = arg
}
obj1 . se t InstVar 5 ( ' E ' )
obj2 . se t InstVar 5 ( ' F ' )
doc ument . wr iteln ( obj1 . ins tVar5 ) // ' E' !!
doc ument . wr iteln ( obj2 . ins tVar5 ) // ' F' !!
COMP284 Scripting Languages Lecture 16 Slide L16 21
(User-defined) Objects Public and private static variables
‘Class’ variables and ‘Class’ methods
Function properties can be used to emulate Java’s class variables
(static variables shared among instances) and class methods
fu nc tion C ircle ( radius ) { this .r = r ad ius }
// ` clas s variable ' - propert y of the C ir cle cons truct or f un ction
Circle . PI = 3.14159
// ` ins ta nc e method '
Circle . p ro totype . are a = f unction () {
return Ci rc le . PI * this .r * this .r; }
// ` clas s m et ho d ' - prope rt y of the C ir cl e co ns tru ct or f unction
Circle . max = functio n (cx , cy ) {
if ( cx . r > cy .r) { r et ur n cx } else { return cy }
}
c1 = new Circle (1.0) / / create an instance of the Circle class
c1 .r = 2.2; // set the r i nstance variabl e
c1 _a re a = c1 . area (); // invoke the area () i ns ta nc e method
x = Math . exp ( C ir cl e . PI ) // use the PI class v ar ia ble in a compu ta tio n
c2 = new Circle (1.2) / / create an ot he r Circle in st ance
bigger = Circle . max ( c1 , c2 ) // use the max () c lass me thod
COMP284 Scripting Languages Lecture 16 Slide L16 22
(User-defined) Objects Public and private static variables
Private static variables
In order to create private static variables shared between objects
we can use a self-executing anonymous function
var Person = ( fu nc ti on () {
var popul at ion = 0 // pri va te stat ic ` cl ass ' varia bl e
return function ( va lue ) { // c onstr uctor
po pulat io n ++
var nam e = v alue // pr iv at e instan ce var ia bl e
this . se tN am e = function ( va lue ) { name = v alue }
this . ge tN am e = function () { r et ur n name }
this . getPop = f un ct ion () { return popul at ion }
}
}())
pe rs on 1 = new P er so n ( ' Peter ' )
pe rs on 2 = new P er so n ( ' James ' )
pe rs on 1 . ge tName () --> ' Pete r '
pe rs on 2 . ge tName () --> ' Jame s '
pe rs on 1 . name --> u ndefine d
Person . p op ula ti on || p er so n1 . po pu latio n --> u ndefine d
pe rs on 1 . ge tP op () --> 2
pe rs on 1 . se tName ( ' Da vid ' )
pe rs on 1 . ge tName () --> ' Davi d '
COMP284 Scripting Languages Lecture 16 Slide L16 23
(User-defined) Objects Pre-defined objects
Pre-defined objects: String
JavaScript has a collection of pre-defined objects,
including Array, String, Date
A String object encapsulates values of the primitive datatype string
Properties of a String object include
length the number of characters in the string
Methods of a String object include
charAt(index)
the character at position index (counting from 0)
substring(start,end)
returns the part of a string between positions start (inclusive)
and end (exclusive)
toUpperCase()
returns a copy of a string with all letters in uppercase
toLowerCase()
returns a copy of a string with all letters in lowercase
COMP284 Scripting Languages Lecture 16 Slide L16 24
(User-defined) Objects Pre-defined objects
Pre-defined objects: String and RegExp
JavaScript supports (Perl-like) regular expressions and the String
objects have methods that use regular expressions:
search(regexp)
matches regexp with a string and returns the start position of the first
match if found, -1 if not
match(regexp)
without g modifier returns the matching groups for the first match
or if no match is found returns null
with g modifier returns an array containing all the matches for
the whole expression
replace(regexp,replacement)
replaces matches for regexp with replacement,
and returns the resulting string
name1 = ' Dave Shi eld '. replace (/(\ w +)\ s (\ w +)/ , " $2 , $1" )
regexp = new RegE xp (" (\\ w +)\\ s (\\ w +) " )
name2 = ' Ken Chan ' . r e p l ace ( regexp , " $2 , $1 " )
COMP284 Scripting Languages Lecture 16 Slide L16 25
(User-defined) Objects Pre-defined objects
Pre-defined objects: Date
The Date object can be used to access the (local) date and time
The Date object supports various constructors
new Date() current date and time
new Date(milliseconds) set date to milliseconds since 1 January 1970
new Date(dateString) set date according to dateString
new Date(year, month, day, hours, min, sec, msec)
Methods provided by Date include
toString()
returns a string representation of the Date object
getFullYear()
returns a four digit string representation of the (current) year
parse()
parses a date string and returns the number of milliseconds
since midnight of 1 January 1970
COMP284 Scripting Languages Lecture 16 Slide L16 26
(User-defined) Objects Pre-defined objects
Revision
Read
Chapter 16: JavaScript Functions, Objects, and Arrays
Chapter 17: JavaScript and PHP Validation and Error Handling
(Regular Expressions)
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2009.
http://coffeeonthekeyboard.com/
private-variables-in-javascript-177/
http://coffeeonthekeyboard.com/
javascript-private-static-members-part-1-208/
http://coffeeonthekeyboard.com/
javascript-private-static-members-part-2-218/
COMP284 Scripting Languages Lecture 16 Slide L16 27