This section provides a quick description of two special loop statements for iterating properties and methods of object. A tutorial example is provided to show the extra properties and methods of two objects of the same type.
JavaScript supports two special loop statements that allows you to iterate all properties and methods in an object:
1. A "for ... in" statement has the following syntax:
for (var item in object_name) {
... statements with object_name[item] ...
}
In this "for ... in" statement, the embedded statements will be executed for each properties and methods.
Variable "item" will contain the current property or method name.
Expression "object_name[item]" uses the associate array format to retrieve the property value.
2. A "for each ... in" statement has the following syntax:
for each (var value in object_name) {
... statements with value ...
}
In this "for each ... in" statement, the embedded statements will be executed for each properties and methods.
Variable "value" will contain the value of the current property or the function of the current method.
Here is a tutorial example that use both "for ... in" and "for each ... in" statements to loop through
all properties and methods:
<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");
// Adding additional property and method to one object
myBook.price = 99.99;
myBook.getDesc = getDescription;
// Showing object properties and methods
showObject(myBook, "myBook");
function showObject(object, name) {
document.writeln("\nShowing object \""+name+"\"");
document.writeln(" Property/method names and values:");
for (var item in object) {
document.writeln(" "+item+": "+object[item]);
}
document.writeln("\nShowing object \""+name+"\"");
document.writeln(" Property/method values:");
for each (var v in object) {
document.writeln(" "+v);
}
}
</script>
</pre>
</body>
</html>
The output of this tutorial example is printed below:
Showing object "myBook"
Property/method names and values:
title: JavaScript Tutorials
author: Herong Yang
price: 99.99
getDesc: function getDescription() {
return "\"" + this.title + "\" by " + this.author;
}
Showing object "myBook"
Property/method values:
JavaScript Tutorials
Herong Yang
99.99
function getDescription() {
return "\"" + this.title + "\" by " + this.author;
}