HTML and CSS Reference
In-Depth Information
EXAMPLE 8.14
4
Book.prototype.addTax=function addTax(){
this.price *= 1.18;
return(this.price.toFixed(2));
}
5
var famousBook=new Book("War and Peace","Leo Tolstoy", 30.00);
var myBook=new Book("JavaScript by Example", "Ellie
Quigley", 25);
6
document.write("<br /><b>" + famousBook.show()+"<br />");
document.write("<br /><b>" + myBook.show()+"<br />");
7
document.write("With tax \""+ famousBook.title +"\" costs $"+
famousBook.addTax() +".<br />");
document.write("With tax \""+ myBook.title + "\" costs $" +
8
myBook.addTax() +".<br />");
</script>
</body>
</html>
EXPLANATION
1
The constructor function called Book defines the properties and methods for a
Book class. ( Book is a JavaScript representation of a class.) The constructor func-
tion has a prototype object containing those properties that are inherited by all
Book objects.
2
A function called showProps is defined on line 3. Its name is assigned to the prop-
erty called show , making it a method for the Book class.
3
The function showProps uses the special for loop to iterate through all the proper-
ties of an object.
4
The Book's prototype property is used to add a function called addTax() . It calcu-
lates and returns the price of the book with an 18 percent sales tax added. This
function will be added as a method to the Book class and available to all objects
in that class. JavaScript creates only one copy of the function and all book objects
will point to that copy.
5
A new Book object, called myBook , is created. It has inherited all of the original
properties of the Book class, including the new method defined by the prototype
property, called addTax .
6
The show() method is called for the object, famousBook . The entire object, prop-
erties and methods are displayed. You can see that addTax has been included.
7
The new method, addTax() is called for the object famousBook .
8
Again, addTax() is called for the object myBook . The result is shown in Figure
8.17.
Search WWH ::




Custom Search