Dr. Dobb's Journal May 1997
JavaScript Objects
JavaScript objects are different from C++ and Java objects; they are not actually objects. They are associative arrays of JavaScript variables. Each property can have any of the JavaScript types: number, string, boolean, object, or function. Additionally, a property can reference another array. If you are used to C++ or Java, it may take you a little time to get used to JavaScript objects. There are two different ways to access a JavaScript object property -- dot notation and associative indexing. If you defined a person object that has the property name, then you can reference that property using any of the following notations:
person.name person["name"] var x="name" person[x]
When you assign a value to an object property using any of these formats, you create a new property if the property did not previously exist. Since new object properties can be dynamically created, it is not always possible to know all the properties associated with a particular object. For this reason, JavaScript supplies a for(in) control structure that lets you iterate over all properties of a particular object. For example, the following loop prints all properties and values of the Person object, even though you added a new property outside the constructor.
var myPerson=new Person() myPerson.likesDonuts=true for(var i in myPerson) document.writeln("myPerson."+i+"="+myPerson[i]+"<BR>")
-- C.B.T.
Copyright © 1997, Dr. Dobb's Journal