COMP519 Web Programming
Lecture 15: JavaScript (Part 6)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 (User-defined) Objects
Object Literals
Object Constructors
Prototype Property
Public and Private Static Variables
for/in-loops
Inheritance
Classes as Syntactic Sugar
2 Pre-defined Objects
Regular Expressions
String
Date
3 Further Reading
COMP519 Web Programming Lecture 15 Slide L15 1
(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
{ memberName1 : value1 , m e m b e r N a m e 2 : value2 , ...}
memberName1, memberName2, . . . are member names
value1, value2, . . . are member values (expressions)
Terminology:
member value is function ; method
member value is some other value ; property
{
age : (30 + 2) ,
gender : male ,
nme : { f i rs t : Ben , last : Budd } ,
inter ests : [ music , skiing ],
he llo : funct i on () { re t u rn Hi ! I \ m + this . nme . first }
};
COMP519 Web Programming Lecture 15 Slide L15 2
(User-defined) Objects Object Literals
Object Literals
Member values can be accessed using dot notation or bracket notation
var person1 = {
age : (30 + 2) ,
gender : male ,
nme : { f i rs t : Ben , last : Budd } ,
inter ests : [ music , skiing ],
he llo : funct i on () { re t u rn Hi ! I \ m + this . nme . first }
};
person1 . age --> 32 // dot no t at ion
person1 [ gender ] --> male // br a ck et n ot ation
person1 . nme . first - - > Ben
person1 [ nme ][ last ] --> Budd
COMP519 Web Programming Lecture 15 Slide L15 3
(User-defined) Objects Object Literals
Object Literals
var person1 = {
...
nme : { first : Ben , last : Budd },
he llo : funct i on () { re t u rn Hi ! I \ m + this . nme . first }
};
person1 . hello () --> " Hi ! I m Ben "
person1 [ hello ]() - -> "Hi ! I m Ben "
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.nme.first is person1.nme.first
COMP519 Web Programming Lecture 15 Slide L15 4
(User-defined) Objects Object Literals
Object Literals
var nme = { first : Adam , last : Alby }
var pe rson1 = {
nme : { first : Ben , last : Budd },
hello : funct ion () { return I\ m + this . nme . first } ,
full1 : this . nme . first + " " + this . nme . last ,
full2 : nme . first + " " + nme . last ,
greet : funct ion () { return I\ m + nme . first }
}
con sole . log ( hello = , p erson1 . hell o ())
hello = Im Ben
con sole . log ( greet = , p erson1 . gree t ())
con sole . log ( full1 = , p erson1 . full 1 )
con sole . log ( full1 = , p erson1 . full 2 )
greet = Im Adam
full1 = Adam Alby
full2 = Adam Alby
COMP519 Web Programming Lecture 15 Slide L15 5
(User-defined) Objects Object Literals
Object Literals
var nme = { first : Adam , last : Alby }
var pe rson1 = {
nme : { first : Ben , last : Budd },
hello : funct ion () { return I\ m + this . nme . first } ,
full1 : this . nme . first + " " + this . nme . last ,
full2 : nme . first + " " + nme . last ,
greet : funct ion () { return I\ m + nme . first }
}
In the construction of the object literal itself, this does not refer to
person1 but its execution context (the window object)
; none of nme.first, nme.last, this.nme.first, and
this.nme.last refers to properties of this object literal
In person1.greet() the execution context of greet() is person1
; but nme.first does not refer to person1.nme.first
Do not think of an object literal as a block of statements (and of
property/value pairs as assignments within that block)
COMP519 Web Programming Lecture 15 Slide L15 6
(User-defined) Objects Object Constructors
Object 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 properties of the object
; each object will have its own copy of these variables
it is possible to make such properties private or public
inner functions will be methods of the object
it is possible to make such functions/methods private or public
private properties/methods can only be accessed by the object itself
public properties/methods can be accessed from outside the object
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
COMP519 Web Programming Lecture 15 Slide L15 7
(User-defined) Objects Object Constructors
Objects: Definition and Use
fu nct io n SomeO bj () {
this . prop1 = A // p ub lic prope rty
var prop2 = B // pr iv ate p rop ert y
// p ub lic metho d
this . m eth od 1 = func tio n () {
// ( use of a) publi c va ria ble must be p rec ede d by this
// ( use of a) pri vate va ria ble mu st NOT be pre ced ed by this
retu rn m1 [ prop1 = + this . p ro p1 + prop2 = + prop2 + ] }
// p riv at e metho d
var me thod2 = fu nct ion () {
retu rn m2 [] }
// p ub lic metho d
this . m eth od 3 = func tio n () {
// ( call of a) p ubl ic met ho d must be pre ced ed by this
// ( call of a) pri vat e me th od must NOT be p rec ed e d by this
retu rn m3 [ + this . m et hod 1 () + + met ho d2 () + ] }
}
obj1 = new Som eO bj () // c rea te s a new object
obj1 . prop1 = A
obj1 . prop2 = un de f ine d
obj1 . m eth od 1 () = m1 [ pr op 1 =A prop2 =B]
obj1 . m eth od 2 () --> Typ eEr ror : obj . met hod 2 is not a fun cti on
obj1 . m eth od 3 () = m3 [ m1 [ pro p1 = A prop2 = B ] m2 []]
COMP519 Web Programming Lecture 15 Slide L15 8
(User-defined) Objects Object Constructors
Objects: Definition and Use
fu nct io n Som eOb j () {
this . prop1 = A // p ub lic pro per ty
var prop2 = B // pr iv ate p rop ert y
var that = thi s
// p riv at e metho d
var me thod4 = fu nct ion () {
// ( use of a) publi c va ria ble must be p rec ede d by that
// ( use of a) pri vate va ria ble mu st NOT be pre ced ed by that
retu rn m4 [ prop1 = + that . p ro p1 + prop2 = + prop2 + ] }
// p riv at e metho d
var me thod6 = fu nct ion () {
// ( call of a) p ubl ic met ho d must be pre ced ed by that
// ( call of a) pri vat e me th od must NOT be p rec ed e d by that
retu rn m6 [ + that . m et hod 1 () + + met ho d2 () + ] }
this . m eth od 5 { ret ur n metho d4 () }
this . m eth od 7 { ret ur n metho d6 () }
}
obj1 = new Som eO bj () // c rea te s a new object
obj1 . m eth od 5 () = m4 [ pr op 1 =A prop2 = B]
obj1 . m eth od 7 () = m6 [ m1 [ pro p1 = A prop2 = B ] m4 [ prop1 =A p ro p2 = B ]]
COMP519 Web Programming Lecture 15 Slide L15 9
(User-defined) Objects Object Constructors
Objects: Definition and Use
fu nct io n Som eOb j () {
this . prop1 = A // p ub lic pro per ty
var prop2 = B // pr iv ate p rop ert y
this . m eth od 1 = func tio n () { // publ ic met ho d
retu rn m1 [ prop1 = + this . p ro p1 + prop2 = + prop2 + ] }
var me thod2 = fu nct ion () { ... } // pri vate meth od
}
obj1 = new Som eO bj ()
obj2 = new Som eO bj ()
co ns ole . log ( obj1 . met hod 3 () = , obj1 . m et hod 3 ())
obj1 . m eth od 3 () = m3 [ m1 [ pro p1 = A prop2 = B ] m2 []]
obj1 . m eth od 1 = func tio n () { ret ur n mod ified }
obj2 . prop1 = C
co ns ole . log ( obj1 . met hod 3 () = , obj1 . m et hod 3 ())
co ns ole . log ( obj2 . met hod 3 () = , obj2 . m et hod 3 ())
obj1 . m eth od 3 () = m3 [ mod ifi ed m2 []]
obj2 . m eth od 3 () = m3 [ m1 [ pro p1 = C prop2 = B ] m2 []]
prop1, prop2, method1 to method2 are all members (instance
variables) of SomeObj
The only difference is that prop1 and prop2 store strings while
method1 and method2 store functions
; every object stores its own copy of the methods
COMP519 Web Programming Lecture 15 Slide L15 10
(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
fun ction SomeObj () {
this . prop1 = A // publi c p roperty
var prop2 = B // pr ivate pr ope rty
Som eObj . p rotot ype . method1 = fun ction () { ... } // publi c
Som eObj . p rotot ype . method3 = fun ction () { ... } // publi c
var me thod2 = function () { ... } // private method
var me thod4 = function () { ... } // private method
}
Note: prototype properties and methods are always public!
COMP519 Web Programming Lecture 15 Slide L15 11
(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 ncti o n So m eOb j () { ... }
obj1 = new Some O bj ()
obj2 = new Some O bj ()
co nso l e . log ( obj 1 . prop 3 ) // undef i ned
co nso l e . log ( obj 2 . prop 3 ) // undef i ned
So meO b j . pro t otype . pro p3 = 'A '
co nso l e . log ( ' obj1 . pr op3 = ' , obj1 . p rop3 )
co nso l e . log ( ' obj2 . pr op3 = ' , obj2 . p rop3 )
So meO b j . pro t otype . pro p3 = 'B '
co nso l e . log ( ' obj1 . pr op3 = ' , obj1 . p rop3 )
co nso l e . log ( ' obj2 . pr op3 = ' , obj2 . p rop3 )
obj1 . prop 3 = 'C ' // cre ates a new pro p erty for obj1
So meO b j . pro t otype . pro p3 = 'D '
co nso l e . log ( ' obj1 . pr op3 = ', obj1 . pr op3 )
co nso l e . log ( ' obj2 . pr op3 = ', obj2 . pr op3 )
'A '
'A '
'B '
'B '
'C '
'D '
COMP519 Web Programming Lecture 15 Slide L15 12
(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
funct i on S om eO bj () { ... }
obj1 = new SomeObj ()
obj2 = new SomeObj ()
SomeObj . p rotot y pe . pr o p 4 = 'E '
SomeObj . p rotot y pe . setPr op 4 = functi o n ( arg ) {
this . prop4 = arg
}
obj1 . set P rop4 (' E ')
obj2 . set P rop4 (' F ')
console . log ( ' obj1 . pr o p 4 = ' , obj1 . prop4 )
console . log ( ' obj2 . pr o p 4 = ' , obj2 . prop4 )
E
F
COMP519 Web Programming Lecture 15 Slide L15 13
(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 objects) and class methods
fu ncti o n Ci rcl e ( ra dius ) { th is . r = radi us }
// class variab le - p rope rty of the C ircle con s t ructo r func t ion
Circl e . PI = 3.14 159
// i nst a nce method
Circl e . pro t otyp e . ar ea = func t ion () {
retur n Circl e . PI * th is . r * this .r ; }
// class method - p r oper ty of the Circ le co n s truct o r func tion
Circl e . max = fu ncti o n ( cx , cy ) {
if ( cx . r > cy .r ) { retu rn cx } else { ret urn cy }
}
c1 = new Circle (1 .0) // cre ate an object of the Circ le class
c1 . r = 2.2; // set the r pr oper t y
c1 _ar e a = c1. area (); // inv oke the area () in stan c e me tho d
x = Math . exp ( Ci rcle . PI ) // use the PI cla ss varia b le in a co m p utati o n
c2 = new Circle (1 .2) // cre ate anot her Cir cle o bje ct
bigge r = Circ le . max (c1 , c2 ) // use the max () cla ss m eth od
COMP519 Web Programming Lecture 15 Slide L15 14
(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 Perso n = ( func tion () {
var pop u latio n = 0 // pri v ate sta tic ` class ' va r iabl e
retur n fu n ctio n ( va lue ) { // c onstr u c t or
po p ulati o n ++
var nam e = value // pri v ate p rope rty
this . se t Nam e = fun c tion ( value ) { name = val ue }
this . ge t Nam e = fun c tion () { ret urn name }
this . ge tPo p = fu ncti o n () { ret urn p opula t ion }
}
}())
pe rso n 1 = new P ers on ( ' Peter ')
pe rso n 2 = new P ers on ( ' James ')
co nso l e . log ( pe rson 1 . get Name () )
co nso l e . log ( pe rson 2 . get Name () )
co nso l e . log ( pe rson 1 . name )
co nso l e . log ( Perso n . popu l ation || pers on1 . p o pulat i o n )
co nso l e . log ( pe rson 1 . ge tPop () )
pe rso n 1 . set Nam e ( ' David ')
co nso l e . log ( pe rson 1 . get Name () )
Pete r
Jame s
un d efin e d
un d efin e d
2
Davi d
COMP519 Web Programming Lecture 15 Slide L15 15
(User-defined) Objects for/in-loops
for/in-loop
The for/in-loop allows us to go through the properties of an object
for (var in obj ect ) { statements }
Within the loop we can use object[var] to access the value of the
property var
var pe rson1 = { age : 32 ,
gender : ' male ' ,
name : 'Bob Smith '
}
for ( prop in person1 ) {
con sole . log ( ' person1 [' + prop + '] has val ue '
+ pers on1 [ prop ]);
}
per son1 [ gender ] has value male
per son1 [ name ] has value Bob Smith
per son1 [ age ] has value 32
COMP519 Web Programming Lecture 15 Slide L15 16
(User-defined) Objects Inheritance
Inheritance
The prototype property can also be used to establish
an inheritance relationship between objects
function Rectan g le ( width , height ) {
this . width = widt h
this . h e i g h t = height
this . type = ' Recta ngle '
this . area = func t i o n () { re t u r n this . width * this . height }
}
function Sq u a r e ( length ) {
this . width = this . height = length ;
this . type = ' Square '
}
// Square i n h er i ts from R e c ta ng le
Square . p r ot ot y pe = new R e ct an gl e ();
var sq1 = new Square (5);
console . log (" The area of sq1 is " + sq1 . area () );
The area of sq1 is 25
COMP519 Web Programming Lecture 15 Slide L15 17
(User-defined) Objects Classes as Syntactic Sugar
Classes as Syntactic Sugar
ECMAScript 2015 introduced classes as syntactic sugar for
prototype-based objects
cl ass Rectang l e {
const r uctor ( width , height ) {
this . width = widt h
this . h e i g h t = height
this . type = ' Recta ngle '
}
get area () { return this . width * this . height }
}
cl ass Square ex t en d s Recta n gl e {
const r uctor ( length ) {
su per ( length , length )
this . type = ' Square '
}
}
var sq1 = npew S q u a r e (5)
console . log (" The area of sq1 is " + sq1 . area ) // not sq1 . area ()!
COMP519 Web Programming Lecture 15 Slide L15 18
Pre-defined Objects Regular Expressions
Pre-defined Objects: RegExp
JavaScript has a collection of pre-defined objects,
including Array, Date, RegExp, String
RegExp objects are called regular expressions
Regular expressions are patterns that are matched against strings
Regular expressions are created via
/ r ege xp / // r egu lar e xp ressi on literal
new RegExp ( regexp ) // conve rt ing a string into a reg exp
There are two methods provided by RegExp:
test(str) Tests for a match in a string, returns true or false
exec(str) Executes a search for a match in the string str,
returns an array with a match or null otherwise
COMP519 Web Programming Lecture 15 Slide L15 19
Pre-defined Objects Regular Expressions
Pre-defined Objects: RegExp
The simplest regular expressions consist of a sequence of
alphanumeric characters and
non-alphanumeric characters escaped by a backslash:
that matches exactly this sequence of characters
/100\ $ / matches "100 $ " in " This 100 $ bill "
There is a range of special characters that match characters other than
themselves or have special meaning
. Matches any character except the newline character \n
\n Matches the newline character \n
\w Matches a ‘word’ character (alphanumeric plus _’)
\s Matches a whitespace character
\d Matches a decimal digit character
/\ w \ d/ ma tch es " P5 ", "51" , and "19" in " COMP5 19 "
COMP519 Web Programming Lecture 15 Slide L15 20
Pre-defined Objects Regular Expressions
Pre-defined Objects: RegExp
There is a range of special characters that match characters other than
themselves or have special meaning
^ Matches beginning of input/line
$ Matches end of input/line
+ Matches the preceding expression 1 or more times
* Matches the preceding expression 0 or more times
[set] Matches any character in set which consists of
characters, special characters and ranges of characters
[^set] Matches any character not in set
/^[ a -z ]+ $ / m atc hes " abc ", "x"
but not "0 abc " , " abc1 " , " ab " , " AB ", ""
/^\ s *[a -z ]+\ s *$ / ma tches " abc " , "x ", " ab "
but not "0 abc " , " abc1 " , " AB " , ""
/^[^ a - z ]+ $ / matches " AB " , "0123"
but not " abc ", "x" , "0 abc "
COMP519 Web Programming Lecture 15 Slide L15 21
Pre-defined Objects Regular Expressions
Pre-defined Objects: RegExp
Regular expressions are created via
/ r ege xp / // r egu lar e xp ressi on literal
new RegExp ( regexp ) // conve rt ing a string into a reg exp
Remember that in a string, the escape character \
has a special meaning, e.g.,
\n stands for a newline character \’ stands for an apostrophe
\w stands for w \s stands for s
\\ stands for \
; additional escape characters are required
in RegExp(’regexp’) versus /regexp/
/\ w \ d/ bec omes new RegExp ( \\ w \\d )
/(\ w +)\ s (\ w +)/ becomes new RegExp ( (\\ w +)\\ s (\\ w +) )
/\((\ d +)\)/ bec omes new RegExp ( \\((\\ d +)\\) )
COMP519 Web Programming Lecture 15 Slide L15 22
Pre-defined Objects String
Pre-defined Objects: String
JavaScript has a collection of pre-defined objects,
including Array, Date, Regular Expression, String
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
COMP519 Web Programming Lecture 15 Slide L15 23
Pre-defined Objects String
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 Shield . replace (/(\ w +)\ s (\ w +)/ , " $2 , $1 ")
regexp = new RegExp ("(\\ w +)\\ s (\\ w +)")
name2 = Ken Chan . replace ( regexp , " $2 , $1 ")
COMP519 Web Programming Lecture 15 Slide L15 24
Pre-defined Objects Date
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
COMP519 Web Programming Lecture 15 Slide L15 25
Further Reading
Revision and Further Reading
Read
Chapter 15: Objects
of R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
Read
Chapter 5: Reference Types: The Object Type
Chapter 6: Object-Oriented Programming
Chapter 7: Anonymous Functions
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
COMP519 Web Programming Lecture 15 Slide L15 26