HTML and CSS Reference
In-Depth Information
Creating custom objects
Creating custom objects is standard practice when working with information in custom appli-
cations. Because JavaScript is an object-oriented language, you should apply proper object-
oriented practices when developing JavaScript applications. In almost all cases, this involves
creating custom objects to encapsulate functionality within logical entities.
For example, the following code creates a book object. This is a dynamic object, meaning
that it's created inline with a variable declaration.
var book = {
ISBN: "55555555",
Length: 560,
genre: "programming",
covering: "soft",
author: "John Doe",
currentPage: 5
}
The object created represents a book. It provides a way to encapsulate into a single ob-
ject the properties that apply to a book—in this case, a book entity. The code specifies five
properties. When using the book variable, you can access all the properties just as with any
other property; if desired, you could output to the screen by placing the values into the DOM.
The properties of an object represent its state, whereas the methods of an object provide
its behavior. At this point, the book object has only properties. To give the book object some
behavior, you can add the following code:
var book = {
ISBN: "55555555",
Length: 560,
genre: "programming",
covering: "soft",
author: "John Doe",
currentPage: 5,
title: "My Big Book of Wonderful Things",
flipTo: function flipToAPage(pNum) {
this.currentPage = pNum;
},
turnPageForward: function turnForward() {
this.flipTo(this.currentPage++);
},
turnPageBackward: function turnBackward() {
this.flipTo(this.currentPage--);
}
}
In the book object, three methods have been added: turnPageForward , turnPageBackward ,
and flipTo. . Each method provides some functionality to the book object, letting a reader move
 
 
Search WWH ::




Custom Search