How do I test if a property exists on a object before reading its value?

Robin Rodricks picture Robin Rodricks · May 2, 2010 · Viewed 23.9k times · Source

I'm attempting to read a property on a series of Sprites. This property may or may not be present on these objects, and may not even be declared, worse than being null.

My code is:

if (child["readable"] == true){
    // this Sprite is activated for reading
}

And so Flash shows me:

Error #1069: Property selectable not found on flash.display.Sprite and there is no default value.

Is there a way to test if a property exists before reading its value?

Something like:

if (child.isProperty("readable") && child["readable"] == true){
    // this Sprite is activated for reading
}

Answer

Greg B picture Greg B · May 2, 2010

Objects in AS3 have the hasOwnProperty method which takes a string argument and returns true if the object has that property defined.

if(myObj.hasOwnProperty("someProperty"))
{
    // Do something
}