This section provides a quick description of adding properties and methods to objects only. A tutorial example is provided on adding 1 extra property and 1 extra method to 1 object only.
After an object has been created from the constructor function,
additional properties and methods can be added to this object only,
using these formats:
Here is tutorial example that creates two objects from "Book()",
and adds 1 extra property and 1 extra method to object "myBook" only:
<html>
<!-- Prototype_Add_Property_and_Method.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Adding Additional Properties and Methods to Objects</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Defining the constructor function for a new object type
function Book(title, author) {
this.title = title;
this.author = author;
}
// 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");
var ckBook = new Book("JavaScript Cookbook", "Yosef Cohen");
// Adding additional property and method to one object
myBook.price = 99.99;
myBook.getDesc = getDescription;
// Showing object properties and methods
showObject(myBook, "myBook");
showObject(ckBook, "ckBook");
function showObject(object, name) {
document.writeln("\nShowing object \""+name+"\"");
document.writeln(" Own Properties and Methods:");
for (var item in object) {
document.writeln(" "+item+": "+object[item]);
}
}
</script>
</pre>
</body>
</html>
The output of the tutorial example shows that properties defined in the constructor function
are added to both objects. But properties and methods added to object "myBook" are for "myBook" only.
Showing object "myBook"
Own Properties and Methods:
title: JavaScript Tutorials
author: Herong Yang
price: 99.99
getDesc: function getDescription() {
return "\"" + this.title + "\" by " + this.author;
}
Showing object "ckBook"
Own Properties and Methods:
title: JavaScript Cookbook
author: Yosef Cohen