简体   繁体   中英

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 property 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM