HTML and CSS Reference
In-Depth Information
EXPLANATION
(
CONTINUED
)
3
A new property, called
publisher,
is assigned to the
book1
object. It is available for
this instance of the object.
4
JavaScript retrieves and displays the value of the publisher for the
book1
object.
5
The second book object does not have access to the
publisher
property. It is
unde-
fined
(see Figure 8.13)
.
Figure 8.13
Defining a new property for an object.
What if in the previous example
book2
we want to add a
publisher
property so that it is
extended to all instances of the Book class? All objects have a prototype property. We can
use the Book's
prototype
property to assign new properties to the Book class that will now
be available to the Book class and any instances of the class; that is, all Book objects will
have the new properties. In Example 8.12, we will add new properties to the Book class.
EXAMPLE
8.12
<html>
<head><title>Object Properties</title>
<script type="text/javascript">
1
function Book(title, author){
this.title =title;
this.author=author;
}
</script>
</head>
<body bgColor="#EOFFFF">
<big>
<script>
2
var book1 = new Book("Kidnapped","R.L.Stevenson");
var book2 = new Book("Tale of Two Cities", "Charles Dickens")
3
Book.prototype.publisher = "Penguin Books";