HTML and CSS Reference
In-Depth Information
EXAMPLE
8.5 (
CONTINUED
)
5
function pageForward()
{ //
Functions to be used as methods
this.pagenumber++;
return this.pagenumber;
}
6
function pageBackward()
{
this.pagenumber--;
return this.pagenumber;
}
</script>
</head>
<body>
<script type = "text/javascript">
7
var myBook = new Book("JavaScript by Example",
"Ellie Quigley", "Prentice Hall" );
//
Create new object
8
myBook.pagenumber=5
; /
Assign a page number
9
document.write( "<b>"+ myBook.title +
"<br>" + myBook.author +
"<br>" + myBook.publisher +
"<br>Current page is " + myBook.pagenumber );
document.write("<br>Page forward: " );
10
for(i=0;i<3;i++){
11
document.write("<br />" +
myBook.uppage()
);
//
Move forward a page
}
document.write("<br />Page backward: ");
for(;i>0; i--){
12
document.write("<br />" +
myBook.backpage()
);
//
Move back a page
}
</script>
</body>
</html>
EXPLANATION
1
This is the constructor function that will represent a class called “Book”. The
function creates the object and assigns it properties and methods. The parameter
list contains the values for the properties
title, author
, and
publisher
. Each time this
function is called a new Book class is instantiated.
2
The
this
keyword refers to the
Book
object. The
Book
object is given a
pagenumber
property initialized to
0
.
3
A method is defined by assigning the function to a property of the
Book
object.
this.uppage
is assigned the name of the function,
pageForward
, that will serve as
the object's method. Note that only the
name of the method
is assigned to a prop-
erty, i.e., a reference to the function's definition. There are no parentheses follow-
ing the name. This is important. If you put parentheses here, you will receive an
error message. But when the method is called you must use parentheses.