HTML and CSS Reference
In-Depth Information
Like any other object, you can assign properties and methods to the prototype object.
You do this with the prototype property. When values are assigned to an object's proto-
type property, they are automatically extended to all instances of the class. After an
object has been created, new properties and methods can be added to the prototype
object, and any objects created after that will automatically inherit the new properties
and methods. This is how JavaScript implements inheritance. It allows you to reuse code
and customize an object.
Let's say we define a constructor function called Book() with a set of properties such
as title and author . The Book() constructor function is JavaScript's way of creating a class.
The constructor function is called with the new keyword and creates an instance of the
Book class, an object called book1 , and then the constructor function is called again and
creates another Book object called book2 , and so on. Now, after creating book1 , we add
another property such as book1.publisher . This property affects book1 , and only book1 .
The publisher property is not extended to book2 . The property would have to be added
separately to each Book object that needs it or by adding it to the Topic's prototype.
Adding a new property without using the prototype property
<head><title>Object Properties</title>
<script type="text/javascript">
function Book(title, author){
this.title =title;;
<body bgColor="#EOFFFF">
var book1 = new Book("Kidnapped","R.L.Stevenson");
var book2 = new Book("Tale of Two Cities", "Charles Dickens")
book1.publisher="Penguin Books";
document.write(book1.title + " is published by "+
book1.publisher + "<br />");
document.write(book2.title + " is published by " +
book2.publisher ); // Doesn't have this property
The constructor function called Book will define the properties and methods for
a Book class. The function takes two parameters.
Two new Book objects are created, book1 and book2 .
Search WWH ::

Custom Search