HTML and CSS Reference
In-Depth Information
Using The Prototype Property
EXAMPLE 8.13
<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
Object.prototype.category="Fiction";
4
Book.prototype.publisher = "Penguin Books";
document.write(book1.title + " is published by "+
5
book1.publisher + " and is in the " + book1.category +
" category <br />");
document.write(book2.title + " is published by "+
book2.publisher + " and is in the " + book1.category +
" category <br />"); </script>
</script>
</big>
</body>
</html>
EXPLANATION
1
The constructor function called Book will define the properties and methods for
a Book class. The function takes two parameters.
2
Two new Book objects are created, book1 and book2 .
3
By assigning a property to the Object object's prototype, all instances of the Book
class (or any class) will have access to the category property. Note that on line 5,
the book uses the category property. (This is just an example to show how the pro-
totype property is used, not meant to be practical.)
4
The Book class has a prototype object. It is assigned a property. Now the publisher
property and its value are available to all Book objects.
5
When JavaScript tries to retrieve the value of the category property, the property
was not directly assigned in the constructor function. JavaScript checks to see if a
Book prototype has been defined in the property. It has not. Going up the chain,
the next level up is the Object object. It does have this prototype property. The val-
ue is retrieved (see Figure 8.16).
Search WWH ::




Custom Search