For a long time I’ve struggled with determining whether or not a property exists in Actionscript 3.0. Like many people, I would often find myself writing somewhat tediously repetitive conditional checks such as:
1 2 3 4 5 |
if (myObject["myProperty"] !=null && myObject["myProperty"] != undefined) { trace("Do the happy dance, my property has a value!"); } |
Other than the fact that this is a lot of code to write (especially when you have a long conditional that checks 10 or 15 properties), this would work “most” of the time. I say most, because if the property you were trying to validate didn’t exist at all (i.e. there is no property name “myProperty” in your object), then you would get a nice “null object reference” error.
Enter hasOwnProperty(). Now, as usual, I’m sure I’m more than a little late in discovering this handy little method, but if it took me this long to find it, then I’m sure there’s more than a few other lost soles out there that are in the same boat, so this one’s for you guys! As defined in the Adobe LiveDocs, the hasOwnProperty method “Indicates whether an object has a specified property defined.” Sounds simple enough, and it really is. Where this becomes useful is when you want to first check for the existence of a property prior to checking its’ value (and thus avoiding the evil null object reference).
Below is a simple ObjectUtils class that I wrote that currently has a single method called “propertyExists”. The propertyExists method simply implements the hasOwnProperty method, then goes a step further to check for a valid (not null or undefined) value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package { /** * ObjectUtils * * @author: Kyle Tyacke */ public class ObjectUtils { public function ObjectUtils() { } /** * Method checks for the existance of a property with name "property", * then verifies that the value of that property is not null or undefined. * * @param object Object The object to validate against. * @param propert String The name of the property to check for. */ public static function propertyExists( object:Object, property:String ):Boolean { if( object.hasOwnProperty( property ) && object[property] ) { return true; } return false; } } } |
To implement this method and check for a valid property, you would do something like this:
1 2 3 4 |
if( ObjectUtils.propertyExists( myObject, "myValue" ) ) { trace("My property brings all the girls to the yard!"); } |
So, what do you think ?