12.3. Object PropertiesProperties are named data containers associated with an object. They are defined by an object's class and then set individually for each object instance. Like variables, object properties can contain any kind of data -- strings, numbers, Booleans, null, undefined, functions, arrays, movie clips, or even other objects. 12.3.1. Referring to PropertiesThe familiar dot operator gives us access to an object's properties. We separate the name of the property from the object it belongs to using a dot (a period), as follows: objectName.propertyName where objectName is the name of our object and propertyName must be a legal identifier that matches the name of some property of objectName. For example, if we have a ball object instance with a radius property, we can access radius using: ball.radius Alternatively, we may refer to a property using the [] operator, as follows: objectName[propertyName] The [] operator allows us to compose a property name using any expression that resolves to a string. For example: trace(ball["radius"]); var prop = "radius"; trace(ball[prop]); // prop resolves to "radius" Built-in ActionScript properties are accessed in exactly the same way. Recall the syntax for retrieving the value of pi: Math.PI In that expression, we're accessing the built-in PI property of the Math object. However, in pure OOP, we'll nearly never access an object's properties directly; instead, we'll use methods to access property values. For example, to check the volume property of an instance of the built-in Sound class, we use: trace(mySound.getVolume( )); not: trace(mySound.volume); 12.3.2. Using a for-in Loop to Access an Object's PropertiesIn Chapter 8, "Loop Statements", we learned that a for-in loop can be used to enumerate the properties of an object. Now that we know a little more about objects, it's worth returning to the for-in statement briefly to review how it can be used to manipulate an object's properties. Like all loops, the for-in statement includes a header and a body. The body of a for-in statement is automatically executed once for each property in the specified object. We don't need to know the number of properties or their names, because as each cycle of the loop executes, our "iterator" variable automatically becomes the name of the next property. We can therefore access the properties of the object, like this: // List all the properties of the ball object for (var prop in ball) { trace("Property " + prop + " has the value " + ball[prop]); } Note that the iterator variable, prop, in the preceding example is not an integer as it would be in a for loop. That is, don't confuse a standard for loop, typically used for accessing numbered array elements, with a for-in loop used to access an object's properties. For more information on for-in loops, see Chapter 8, "Loop Statements". Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|