This section provides a tutorial example on how to build multiple levels of prototype objects. It also shows how to override an inherited property with a local property.
As a summary of object property inheritance through multiple levels of prototype objects,
I wrote this tutorial example to use "myBook" as a prototype to define an "EBook" constructor function:
<html>
<!-- Inheritance_Multiple_Level_Prototypes.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Building Multiple Level Prototypes</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Modifying the base prototype object
Object.prototype.copyright = "herongyang.com";
</script>
<script type="text/javascript">
// Defining the "Book" constructor
function Book(title, author) {
this.title = title;
this.author = author;
this.getDesc = getDescription;
}
function getDescription() {
return "\""+this.title+"\" by "+this.author;
}
var myPrototype = new Object();
Book.prototype = myPrototype;
Book.prototype.price = 9.99;
Book.prototype.constructor = Book;
Book.prototype.toString = getString;
function getString() {
return this.author+"/"+this.title+"/"+this.price;
}
</script>
<script type="text/javascript">
// Defining the second level constructor "EBook"
function EBook(url) {
this.url = url;
}
var myBook = new Book("Programming Tutorials", "Herong Yang");
EBook.prototype = myBook;
Book.prototype.constructor = EBook;
// Creating an object of "EBook"
var myEBook = new EBook("www.herongyang.com");
// Adding a local property
myEBook.title = "JavaScript Tutorials";
// Showing properties of this object
showObject(myEBook, "myEBook");
function showObject(object, name) {
document.writeln("\n\""+name+"\" properties:");
for (var item in object) {
if (object.hasOwnProperty(item))
var inheritance = "Local";
else
var inheritance = "Inherited";
document.writeln(" "+item+": "+inheritance+": "
+object[item]);
}
}
</script>
</pre>
</body>
</html>
The output of this tutorial example confirms that object "myEBook" inherits
from "EBook.prototype", "Book.prototype", and "Object.prototype".
Notice "myEBook" has a local property "title" overrides the inherited property "EBook.prototype.title":