JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.10

Inheriting from Constructor's Prototype Object

This section provides a quick description of how object inheriting properties and methods from its constructor's prototype object. A tutorial example and diagram is provided to show relations of an object, its constructor, and the constructor's prototype object.

From previous chapters in this book, we learned that:

  • A constructor is a function. But it is also an object.
  • Each constructor has built-in default property called "prototype".
  • The constructor's "prototype" is an object.
  • Properties and methods can be added to the constructor's prototype object.
  • Each object will inherit properties and methods from its constructor's prototype object.

To demonstrate those rules, I wrote the following tutorial example to allow "myBook" to inherit the "price" property from the constructor's prototype object:

<html>
<!-- Inheritance_from_Prototype.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Inheritance from Prototype</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;

   // 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");

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 what we learned earlier:

"myBook" properties:
   title: JavaScript Tutorials
   author: Herong Yang
   price: 9.99

"Book" properties:
   prototype: [object Object]

"Book.prototype" properties:
   price: 9.99

The output can also be represented with this diagram:
Inheritance from Prototype

Sections in This Chapter

Inheriting from Constructor's Prototype Object

Changing the Constructor's Prototype Object

Inheriting Properties from Two Level Prototype Objects

Built-in Properties and Methods in "Object.prototype"

Using "hasOwnProperty()" Method to Test Inherited Properties

Setting the "constructor" Property in the "prototype" Object

Adding Local Methods at the Object Level

Adding Inherited Methods at the Prototype Level

Building Multiple Levels of Prototype Objects

Prototype Object Chain Summary

Dr. Herong Yang, updated in 2008
Inheriting from Constructor's Prototype Object