So, I had a situation where I was receiving an object of an unknown class type and I needed to make a copy of it. Because it had read-only properties that were set through the constructor, I couldn’t just create my copy through ObjectUtils. I had seen many times in the Live Docs a listing for a public property called constructor. It’s public and originates on Object, so everything should have it. Looking at the documentation, it looked like I could use it to instantiate another instance of the same class as the mystery class type.
In this instance, I had was dealing with classes that extended Event. In the documentation, constructor is listed as a public property that is inherited from Object. The prototype property is the same way. However, whenever I tried to access the constructor property on my extended class, the Flex compiler would pitch a fit. It certainly wasn’t coming up in the code hinting. Hmm. So I tried to access it on an instance of a straight up Event. It didn’t come up in the code hinting, but it did compile. Hmm again.
With some prompting from John, I tried accessing it on my extended classes using square bracket notation: myEvent['constructor']. That worked. It is a mystery to me why I can access it through square bracket notation, but it won’t come up in code hinting or compile, but it can compile for Event. Anyway, here’s what I did to make a new instance of an existing class instance:
var constructorMethod:Object = mysteryEvent[ 'constructor' ];
var newEvent:MyEvent = new constructorMethod( type );
for( var i:String in mysteryEvent)
{
newEvent[ i ] = mysteryEvent[ i ];
}