How can I tell if an Actionscript object has a certain dynamic property on it?
I have a dynamic Actionscript class as follows:
public dynamic class Foo {....}
In my code I (may) add some properties to it:
myFoo["myNewDynamicProp"] = "bar";
Elsewhere in my code, given an instance of class Foo, how can I determine if that dynamic prop开发者_运维问答erty has been added already without throwing an expensive exception?
You can do one of three things. First, calling a property that doesn't exist on a dyanmic instance doesn't throw an exception. It just returns undefined
, so you can just test for that. Or you can use the in
keyword. Or you can use the hasOwnProperty()
method.
Consider the following:
var myFoo:Foo = new Foo();
myFoo.newProp = "bar";
trace(myFoo.newProp != undefined); // true
trace(myFoo.nothing != undefined); // false
trace("newProp" in myFoo); // true
trace("nothing" in myFoo); // false
trace(myFoo.hasOwnProperty("newProp")); // true
trace(myFoo.hasOwnProperty("nothing")); // false
You could also just as easily use bracket notation for the first example: myFoo['nothing']
Use the hasOwnProperty(property name) method for that :
if (myFoo.hasOwnProperty("myNewDynamicProp")) {
// do whatever
}
You can also loop through the properties of any dynamic class using this:
for (var propertyName:String in myFoo)
{
trace("Property " + propertyName + ": " + myFoo[propertyName]);
if (propertyName == "myNewDynamicProp")
{
// found
// may be do something
}
}
This way you can not only check for your desired property, but also do more with the overall (dynamic) class properties.
You should just be able to do a simple null check like this:
if(myFoo.myNewDynamicProp) {
//you can access it
}
Hope that helps
精彩评论