views:

23

answers:

1

In AS2, I can certainly do this:

var instance = new MyClass();

But is there a way to do something like this?

var constructor = MyClass;
var instance = new constructor();

This appears to be possible in AS3 by just calling "new" on an instance of the Class object, but I haven't been able to figure out what the syntax would be to get this working in AS2.

A: 

You can do that :

First, you must declare the class for include it in the swf.

var toto:YOUR_CLASS;

And next you can get an instance by :

var instance = new["directory.subdirectory.YOUR_CLASS"]();  

Edit:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:at="at.controls.*" creationComplete="init()">
    <mx:Script>
        <![CDATA[
            import mx.rpc.remoting.mxml.RemoteObject;
            private function init():void {
                var obj:Object = ObjectLoader.getInstanceOf(RemoteObject);
            }
        ]]>
    </mx:Script>
</mx:Application>  

ObjectLoader:

package {
    public class ObjectLoader {
        public function ObjectLoader(){
        }

        public static function getInstanceOf(cl:Class):Object {
            return new cl;
        }
    }  

This is a new example. I create an instance of RemoteObject. }

Epharion
Is there a way to do it without knowing the *name* of the class either (or, alternatively, to derive the name from the Function object)?
Mag Roader
If you don't know the name of the class. The compilator don't know either. Your Swf file only contains declared class on your source code.
Epharion
Basically I want to be able to pass a Class reference to another function, and have the other function construct the instance. This would mean I did reference the class at some point (and it is compiled into the SWF); I just didn't reference it at the location where I instantiated it.
Mag Roader
I edited my previous post...
Epharion
Unfortunately your answer is for ActionScript 3, not 2.
Mag Roader