HTML and CSS Reference
In-Depth Information
EXAMPLE 8.10 ( CONTINUED )
4
function show(obj, name) {
// Function to show the object's properties
var result = "";
5
for (var prop in obj) {
6
result += name + " . "+ prop +"="+
obj[prop] + "<br />";
}
7
return result;
}
</script>
</head>
<body bgcolor="lightblue">
<script type="text/javascript">
8
myBook = new book("JavaScript by Example", "Ellie",
"Prentice Hall");
9
document.write("<br /><b>" + myBook.show(myBook, "myBook" ));
</script>
</body>
</html>
EXPLANATION
1
The function called book will define the properties and methods for a book object.
The function is a template for the new object. An instance of a new book object
will be created when this constructor is called.
2
This is the first property defined for the book object. The this keyword refers to
the current object.
3
A show property of the object is assigned a function name also called show , thus
creating a method for the object.
4
The function called show() is defined, tasked to display all the properties of the
object.
5
The special for/in loop executes a set of statements for each property of the object.
6
The name and value of each property is concatenated and assigned to a variable
called result . The value obj[prop] is used to key into each of the property values of
the book object.
7
The value of the variable result is sent back to the caller. Each time through the
loop, another property and value are displayed.
8
A new book object called myBook is created (instantiated).
9
The properties for the topic object are shown in the browser window; see Figure
8.12. Notice how the method and its definition are displayed.
Search WWH ::




Custom Search