Tuesday, November 18, 2008

Flex - Check if a property exists in an Object

When dealing with typeCasting its essential to test if the objects are compatible before having a
typecast statement.Forgetting to do this results in fragile code that might throw a type cast error anytime.
Here is an example that shows you how to test this.

Note:A child is a type of parent and the vice versa is not true.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
creationComplete="test()"
xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.CollectionEvent;
import mx.collections.ArrayCollection;

private function test():void {
var parent:Parent = new Parent();
var child:Child = new Child();

if (child is Parent) {

Alert.show("Yes");

} else {

Alert.show("No");

}

}

]]>

</mx:Script>

</mx:Application>

}



Bookmark and Share

5 comments:

Anonymous said...

Aren't you testing the types here.. Not that it exists, because it clearly does, you created it.

So you are comparing a instance of Parent to a instance of Child.

Anonymous said...

to check if a property exists in an object do this...

if(object.hasOwnProperty("propertyName"))

Ravi said...

Your title is misleading.

Big I said...

thanks guy who commented second, that's what i was looking for, not sure what this tutorial is about

Anonymous said...

The title and the contents dont seem to match.