HTML and CSS Reference
In-Depth Information
In the preceding code, the Book object is constructed so that you can create one with
default properties set. Then, the code creates an Array containing a list of topics. You can
access each element of the array to initialize each Book object as it's needed.
Accessing each Book element to provide initialization values isn't terribly efficient. It would
be more convenient if the Book object supported more than one constructor. That way, you
could create a blank book or create one with specific unique properties. This is where proto-
typing comes in handy. The following code creates a prototype containing two constructors
that support the needs of any users of the Book object:
function Book()
{
//just creates an empty book.
}
function Book(title, length, author) {
this.title = title;
this.Length = length;
this.author = author;
}
Book.prototype = {
ISBN: "",
Length: -1,
genre: "",
covering: "",
author: "",
currentPage: 0,
title: "",
flipTo: function FlipToAPage(pNum) {
this.currentPage = pNum;
},
turnPageForward: function turnForward() {
this.flipTo(this.currentPage++);
},
turnPageBackward: function turnBackward() {
this.flipTo(this.currentPage--);
}
};
var books = new Array(new Book(), new Book("First Edition",350,"Random"));
With this new code, you can create an empty Book object by using the constructor with no
parameters, or you can create a Book object by using specific parameters to initialize some
fields.
Search WWH ::




Custom Search