简体   繁体   中英

Dynamically Invoke Property in AS3

I would like to dynamically invoke a Class 's Property via a String . In the following code, I can dynamically invoke a Class 's Function via a String .

var myClass:Class = getDefinitionByName("myPackage.MyClass") as Class;
myClass["myStaticMethod"]();

where MyClass is defined as:

package myPackage {
    public class MyClass {
         public function MyClass() {}
         public function myMethod():void {};
         public static function myStaticMethod():void {};
         public static function get myProperty():Object { return null; }
    }
}

However, a Property , such as MyClass.myProperty is not a Function . So,

var myClass:Class = getDefinitionByName("myPackage.MyClass") as Class;
myClass["myProperty"]();

throws an error: TypeError: Error #1006: value is not a function because myProperty is not a Function .

Is there any way to do this dynamically via String s?

Thanks for the help.

To solve this issue, I simply needed to remove the () from the code. That is, the new code looks like:

var myClass:Class = getDefinitionByName("myPackage.MyClass") as Class;
myClass["myProperty"]; // This works.

The Answer of Alex will indeed works properly, but only if you have the String written properly. Else you get this error thrown at you: TypeError: Error #1006: value is not a function. To avoid this you could try test if the property or method is defined before using it. Like so:

if(myClass["myProperty"] != undefined) 
{
...
}

Anyhow, in your specific example you are requesting a getter, and that's why you had to remove the () from your source. If you would be needing a method, I would also recommend you to save the method as a function:

var myFunction: Function = myClass["theFunction"];

And then to use either the call or the apply methods.

myFunction.call(null, myParam);

IF you are interested in studying all the methods that an Object has and comparing them to a String. Consider also:

var child:Sprite = new Sprite();
var description:XML = describeType(child);
var methodList: XMLList = description.descendants('method');

The attributes of a <method/> node are:

  • name : The name of the method.
  • declaredBy : The class that contains the method definition.
  • returnType : The data type of the method's return value.

I hope this helps out, let me know if you found it useful.

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