H3XED

ActionScript 3: Determine if Object Property Exists

May 20, 2012   Programming   Nick Vogt   Comments
Please note that this post is over a year old and may contain outdated information.
There are two common methods to determine if a property/attribute/variable of some object exists. Both use the property name as a string and neither rely on checking for an error report.

The first is using the hasOwnProperty method:

var myObject:Object = {name: 'Jenkins'};

if (myObject.hasOwnProperty('name')) {
   // Do something
}

This method is available in any native ActionScript 3 class, but will not be available in your custom classes if they do not extend a native class.


The second method is using the in operator:

var myObject:Object = {name:'Jenkins'};

if ('name' in myObject) {
   // Do something
}

In addition to being shorter, it will also work in custom classes. And best of all, it is a little over twice as fast in most circumstances! It is faster both when checking for properties of native ActionScript 3 classes and custom classes, regardless of whether they extend a native class or not.
Share This Post
Twitter

Comments (0)

Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter