This section provides a quick description of adding local methods at the object level through the constructor function to all objects or directly on one object.
Now we have a good picture of where properties and methods are stored and accessed through the inheritance path.
We are ready to add local methods at the object level - in objects themselves, not their prototype object.
This can be done in two ways:
Add the local method in the constructor function, so all objects created by this constructor will have this local method.
Add the local method to one object only, so other objects will not have this local method.
Let's try to add a method called "getDesc" in the "Book()" constructor function as shown in this tutorial example:
<html>
<!-- Inheritance_Add_Local_Method.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Adding a Local Method through the Constructor</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 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;
// 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 is this method located
document.writeln("\nChecking Object.prototype...");
dumpProperty(Object.prototype, "getDesc");
document.writeln("\nChecking Book.prototype...");
dumpProperty(Book.prototype, "getDesc");
document.writeln("\nChecking myBook...");
dumpProperty(myBook, "getDesc");
// Running this method
document.writeln("\nRunning myBook.getDesc()...");
document.writeln(" "+myBook.getDesc());
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 "getDesc" is a local method at the object level:
Checking Object.prototype...
getDesc: Inherited: undefined
Checking Book.prototype...
getDesc: Inherited: undefined
Checking myBook...
getDesc: Local: function getDescription() {
return "\"" + this.title + "\" by " + this.author;
}
Running myBook.getDesc()...
"JavaScript Tutorials" by Herong Yang
See the next section on how to add a method at the prototype level.