This section provides a quick description of how constructor's prototype objects form a two-level inheritance. A tutorial example is provided to show object property inheritance from first and send level prototype objects.
Now we know how an object inherits properties from its constructor's prototype object.
Since the constructor's prototype object can also inherit properties from its own constructor's prototype object,
an object can inherit properties from its own prototype object and the prototype's prototype object.
To show you this two-level inheritance feature, I wrote this tutorial example below
to allow "myBook" inherit properties from the "price" property from the first level prototype
and the "copyright" property from the second level prototype:
<html>
<!-- Inheritance_from_Second_Level_Prototype.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Inheriting Properties from the Second-Level Prototype Object</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Define the constructor: "Book"
function Book(title, author) {
this.title = title;
this.author = author;
}
// Adding a property to the "prototype"
Book.prototype.price = 9.99;
// Adding a property to the prototype's "prototype"
// Book.prototype's constructor is Object
Object.prototype.copyright = "herongyang.com";
// Creating an object: "myBook"
var myBook = new Book("JavaScript Tutorials", "Herong Yang");
// Showing the object, constructor, and prototype
showObject(myBook, "myBook");
showObject(Book, "Book");
showObject(Book.prototype, "Book.prototype");
showObject(Object.prototype, "Object.prototype");
function showObject(object, name) {
document.writeln("\n\""+name+"\" properties:");
for (var item in object) {
document.writeln(" "+item+": "+object[item]);
}
}
</script>
</pre>
</body>
</html>
The output of this tutorial example confirms that JavaScript allows objects
to inherit properties from its parent prototype objects of multiple levels: