AS3 Quick Tip: Object setPropertyIsEnumerable

Most ActionScript developers are very familiar with Anonymous Objects in ActionScript 3.0 as they provide a convenient mechanism from which properties of an object which are not known at design time can be defined at runtime. This post is just a quick tip on the Object.setPropertyIsEnumerable() method, for more detailed information on using Objects in ActionScript 3.0 visit livedocs.

The Object class has a few useful methods, specifically toString();, hasOwnProperty(); and propertyIsEnumerable();. There is also another method of the Object class which is very useful: setPropertyIsEnumerable() which can be utilized to explicitly omit a property from being included in an enumeration of an object.

Consider the following example:

When enumerating the object instance all properties and their values can easily be retrieved, however it is important to keep in mind that when enumerating an Object the order in which properties are retrieved is not guaranteed. So executing the same loop against the same object instance could yield different results each time, such as “value B, value A, value C” as opposed to what you might have expected, i.e. “value A, value B, value C”.

Now suppose you do not want a property to be exposed via an enumeration of the object, this can be achieved via:

So based on the above examples, if we did not want to expose the “propA” property in a for in… loop we could omit the property as follows:

So when you need to omit properties from being included in an enumeration of an object, Object.setPropertyIsEnumerable(); proves very useful.

{ 3 comments to read ... please submit one more! }

  1. The ability to enumerate an object’s properties can be very useful, yet i don’t really see the draw since you can’t retrieve the public properties but only properties that were dynamically declared (just like in your example).

  2. This is because the enumerable properties are only those which have been defined by the Object instance; not an instance of a specific type. However with that being said you could just as well use introspection (i.e. describeType…) to retrieve all public properties defined by an an object’s class Object, and from that, iterate over the properties and reference them against the class instance.

    Best,
    Eric

  3. i don’t really use the object class but when i do it is to store dynamic variables as you showed here but honnestly i would never set the isPropertyEnumerable to false otherwise…but still, it is a nice tip! tx

{ 0 Pingbacks/Trackbacks }