HTML and CSS Reference
In-Depth Information
Figure 8.16 Going up the prototype chain.
8.5.3 Adding Methods with Prototype
JavaScript methods are just properties that have been assigned functions for their values.
A common use for prototypes is to extend a class by giving it new methods. You can use
a prototype to assign methods that are common to all objects in a given class. The benefit
of using the prototype is that the method does not have to be created and initialized
every time an object is created, and there is no duplication of function code. All objects
in the class share the same prototype method.
In Example 8.14, a new method is defined for the Book class to add a tax to the price
of each book. All Book objects will have access to this method.
<head><title>Method Inheritance</title>
<script type = "text/javascript">
function Book(title, author, price) { // The Book constructor
this.title = title; // Book properties/attributes = author;
2; // Book method
function showProps(){
var result = "";
for (var i in this){
result += i + " = " + this[i] + "<br />";
return result;
<script type="text/javascript">
// Add a new method with prototype
Search WWH ::

Custom Search