This section provides a quick description of adding inherited methods at the constructor's prototype object to allow all objects created by the constructor to share.
In the previous section, we learned how to add a local method to all objects through the constructor function.
However if a method needs to be used by all objects, it's better to add it as an inherited method
in the prototype object. This saves the extra storage required in each object to store a local method.
Let's try to add a method called "toString" in the "Book.prototype" object.
This "toString method will be inherited by all objects created by "Book()".
By the way, "Book.prototype.toString" will override "Object.prototype.toString"
in the inheritance tree.
<html>
<!-- Inheritance_Add_Inherited_Method.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Adding a Inherited Method in the Prototype</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Setting up my constructor, prototype and object
function Book(title, author) {
this.title = title;
this.author = author;
this.getDesc = getDescription;
}
// Defining a function to be used as a local method
function getDescription() {
return "\""+this.title+"\" by "+this.author;
}
// Replacing the default prototype object
myPrototype = new Object();
Book.prototype = myPrototype;
Book.prototype.price = 9.99;
Book.prototype.constructor = Book;
// Adding an inherited method in the prototype
Book.prototype.toString = getString;
// Defining a function to be used as an inherited method
function getString() {
return this.author+"/"+this.title+"/"+this.price;
}
// Modifying the base prototype object
Object.prototype.copyright = "herongyang.com";
// Creating an object from my constructor
var myBook = new Book("JavaScript Tutorials", "Herong Yang");
// Where are these methods located
document.writeln("\nChecking Object.prototype...");
dumpProperty(Object.prototype, "getDesc");
dumpProperty(Object.prototype, "toString");
document.writeln("\nChecking Book.prototype...");
dumpProperty(Book.prototype, "getDesc");
dumpProperty(Book.prototype, "toString");
document.writeln("\nChecking myBook...");
dumpProperty(myBook, "getDesc");
dumpProperty(myBook, "toString");
// Running these methods
document.writeln("\nRunning myBook.getDesc()...");
document.writeln(" "+myBook.getDesc());
document.writeln("\nRunning myBook.toString()...");
document.writeln(" "+myBook.toString());
function dumpProperty(object, property) {
var inheritance;
if (object.hasOwnProperty(property))
inheritance = "Local";
else
inheritance = "Inherited";
document.writeln(" "+property+": "+inheritance+": "
+object[property]);
}
</script>
</pre>
</body>
</html>
The output of this tutorial example confirms that "toString" is an inherited method at the prototype level: