HTML and CSS Reference
In-Depth Information
EXAMPLE 8.12 ( CONTINUED )
document.write(book1.title + " is published by "+
4
book1.publisher + "<br />");
document.write(book2.title + " is published by " +
book2.publisher );
</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
The Book class has a prototype object. It is assigned a property called publisher .
Now the publisher property and its value are available to all Book objects.
4
In the last example only book1 got the new property. Now both book1 and book2
have inherited the publisher property found in the Book's prototype (see Figure
8.14). If you don't want all topics to be published by “Penguin Books” you could
set the value of the publisher to “Unknown” as a default and change it later; for
example, book2.publisher=“Viking Press” and the book2 object would get the value
“Viking Press.”
Figure 8.14 Using the prototype for inheritance.
8.5.2 The Prototype Lookup Chain
When the program tries to retrieve an object's property, JavaScript first looks to see if the
property was defined directly for that object; for example, does the Book object have a
title property? Does the Book object have a author property? If so, JavaScript retrieves
the property. If the property has not been defined, then JavaScript looks at the object's
prototype to see if the property is defined there. If it is not defined there, JavaScript will
go up to the parent object. This process of going up the hierarchy, called the prototype
 
 
Search WWH ::




Custom Search