简体   繁体   中英

How do I get or set a static property on an instance of a class in ActionScript3

For example, I have multiple classes like so:

MyClassA.propertyAlpha
MyClassB.propertyTango
MyClassC.propertyBravo
MyClassD.propertyBeta
MyClassE.propertyCharlie
MyClassF.propertyRoger
MyClassG.propertyWilco

I get an instance of a class of one of the above types and a name of a static property (doesn't matter why).

How do I get or set the static property with just that information (doesn't matter why)?

You can't access the value directly on the instance. It is a property of its class, hence it must be accessed on that.

There are two ways to do this.

Either use the constructor property:

function getStaticProperty( instance:Object, property:String ) : * {
    return instance.constructor[property];
}

Or use getQualifiedClassName and getDefinitionByName to get the class, then get the property value:

function getStaticProperty( instance:*, property:String ) : * {
    var className:String = getQualifiedClassName( instance ).replace("::",".");
    var clazz:Class = getDefinitionByName( className ) as Class;
    return clazz[property];
}

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