This section provides a quick description of the built-in 'prototype' property on the constructor function. A tutorial example is provided on how to store properties and methods in the 'prototype' property to be inherited by all objects created by the constructor.
In previous sections, we learned that a constructor can be used to create new objects.
But a constructor also carries a built-in property called "prototype", which provides
the mechanism to allow objects to share and inherit properties and methods.
A constructor is also an object of the "Function" type.
A constructor can its own properties as an object.
Every constructor has a default property called "prototype".
The default "prototype" property of a constructor is an object.
New properties and methods can be added to the constructor's "prototype" object.
All properties and methods of the constructor's "prototype" object are shared by all objects created from this constructor.
Let's test this out using the following tutorial example:
<html>
<!-- Prototype_Property_on_Constructor.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>The "prototype" Property on the Constructor Function</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Defining object type constructor function
function Book(title, author) {
this.title = title;
this.author = author;
}
// Adding properties and methods to the "prototype"
Book.prototype.price = 9.99;
Book.prototype.getDesc = getDescription;
// Defining a function to be used as a method
function getDescription() {
return "\""+this.title+"\" by "+this.author;
}
// Creating an object of "Book"
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("\nShowing object \""+name+"\"");
document.writeln(" Type: "+(typeof object));
document.writeln(" Property/method names and values:");
for (var item in object) {
document.writeln(" "+item+": "+object[item]);
}
}
</script>
</pre>
</body>
</html>
The output of this tutorial example shows that how the properties and methods of the "prototype" are inherited
by the object:
Showing object "myBook"
Type: object
Property/method names and values:
title: JavaScript Tutorials
author: Herong Yang
price: 9.99
getDesc: function getDescription() {
return "\"" + this.title + "\" by " + this.author;
}
Showing object "Book"
Type: function
Property/method names and values:
prototype: [object Object]
Showing object "Book.prototype"
Type: object
Property/method names and values:
price: 9.99
getDesc: function getDescription() {
return "\"" + this.title + "\" by " + this.author;
}