HTML and CSS Reference
In-Depth Information
EXAMPLE
8.4
<script type="text/javascript">
1
function Book(){
//
Create a Book class
2
this.title = "The White Tiger"; //
Properties
this.author = "Aravind Adiga";
}
3
var bookObj = new Book;
//
Create new Book object
alert(bookObj.title + " by " + bookObj.author);
</script>
EXPLANATION
1
The
Book()
function defines a class. When called with the
new
keyword, the func-
tion acts as a constructor function.
2
The properties describe the characteristics or attributes of the object. The
this
key-
word is a reference to the current object. The title and author are defined for this
book object.
3
A new Book object is created and a reference to it assigned to the variable
bookObj.
The
new
keyword, used with the
Book()
function, causes the function to behave as
a constructor. You can create as many book objects as you want, but in this exam-
ple, they would all have the same title and author. See Figure 8.5 for the output.
Figure 8.5
An instance of the Book class.
EXAMPLE
8.5
<html>
<head><title>User-defined objects</title>
<script type ="text/javascript">
1
function Book
(title, author, publisher){ //
Receivin
g
//
parameters
2
this.pagenumber=0;
//
Properties
this.title = title;
this.author = author;
this.publisher = publisher;
3
this.uppage = pageForward;
//
Create methods
4
this.backpage = pageBackward;
}
Continues