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
EXAMPLE 8.11
</html>
<head><title>Object Properties</title>
1
<script type="text/javascript">
function Book(title, author){
this.title =title;
this.author=author;
}
</script>
</head>
<body bgColor="#EOFFFF">
<big>
<script>
2
var book1 = new Book("Kidnapped","R.L.Stevenson");
var book2 = new Book("Tale of Two Cities", "Charles Dickens")
3
book1.publisher="Penguin Books";
document.write(book1.title + " is published by "+
4
book1.publisher + "<br />");
document.write(book2.title + " is published by " +
5
book2.publisher ); // Doesn't have this property
</script>
</big>
</body>
</html>
EXPLANATION
1
The constructor function called Book will define the properties and methods for
a Book class. The function takes two parameters.
2
Two new Book objects are created, book1 and book2 .
Continues
 
Search WWH ::




Custom Search