title: How to dynamically create an Actionscript 2 MovieClip based class with
body: <p>I have a helper method has been created which allows a MovieClip-based class in code and have the constructor called.  Unfortunately the solution is not complete because the MovieClip callback <b>onLoad()</b> is never called. </p>
  
  <p>(Link to the <a href="http://www.flashdevelop.org/community/viewtopic.php?f=13&amp;t=458" rel="nofollow noreferrer">Flashdevelop thread</a> which created the method .)</p>
  
  <p>How can the following function be modified so both the <b>constructor</b> and <b>onLoad()</b> is properly called.</p>
  
  <pre><code>    //------------------------------------------------------------------------
      //  - Helper to create a strongly typed class that subclasses MovieClip.
      //  - You do not use "new" when calling as it is done internally.
      //  - The syntax requires the caller to cast to the specific type since 
      //    the return type is an object. (See example below).
      //
      //  classRef, Class to create 
      //  id,       Instance name
      //  ...,      (optional) Arguments to pass to MovieClip constructor
      //  RETURNS   Reference to the created object 
      //  
      //  e.g., var f:Foo = Foo( newClassMC(Foo, "foo1") );
      //
      public function newClassMC( classRef:Function, id:String ):Object 
      {
        var mc:MovieClip = this.createEmptyMovieClip(id, this.getNextHighestDepth()); 
        mc.__proto__ = classRef.prototype; 
  
        if (arguments.length &gt; 2) 
        {
          // Duplicate only the arguments to be passed to the constructor of
          // the movie clip we are constructing.
          var a:Array = new Array(arguments.length - 2);
          for (var i:Number = 2; i &lt; arguments.length; i++)
            a[Number(i) - 2] = arguments[Number(i)];
  
          classRef.apply(mc, a);
        }
        else
        {
          classRef.apply(mc);
        }
  
        return mc; 
      }
  </code></pre>
  
  <p>An example of a class that I may want to create:</p>
  
  <pre><code>class Foo extends MovieClip
  </code></pre>
  
  <p>And some examples of how I would currently create the class in code:</p>
  
  <pre><code>// The way I most commonly create one:
  var f:Foo = Foo( newClassMC(Foo, "foo1") );
  
  // Another example...
  var obj:Object  = newClassMC(Foo, "foo2") );
  var myFoo:Foo   = Foo( obj );
  </code></pre>