2 Replies Latest reply on Jul 18, 2006 5:45 AM by Kiriran

    AS3: apply() on constructor

    Kiriran
      Hi

      I'm trying to call the constructor with apply(). I do this because I don't know until runtime how many arguments I have to pass to the constructor.
      here a little code

      Thanks :)
        • 1. Re: apply() on constructor
          Level 7
          Have you tried
          var instance:Object = new classRef(args);

          I don't have the F9AS3 preview installed here so I can't try it out.


          "Kiriran" <webforumsuser@macromedia.com> wrote in message
          news:e9ih6a$2jj$1@forums.macromedia.com...
          > Hi
          >
          > I'm trying to call the constructor with apply(). I do this because I
          don't
          > know until runtime how many arguments I have to pass to the constructor.
          > here a little code
          >
          > Thanks :)
          >
          > package
          > {
          > import flash.utils.getDefinitionByName;
          >
          > public function Test() {
          > // will be dynamic. But assume I have
          > // loaded Foo into the libary so I can
          > // load it via getDefinitionByName
          > var className:String = "Foo";
          >
          > // array with arguments I want to pass
          > // to the Foo constructor. Again, assume
          > // this will be dynamicly generated
          > var args:Array = ["Hello", "World"];
          >
          > // load the class
          > var classRef:Class = getDefinitionByName(className) as Class;
          >
          > // now the problem. how can I pass
          > // those arguments? I figured out
          > // there has to be a way with apply()
          >
          > // this don't work
          > var instance:Object = new classRef.apply(null, args);
          > }
          > }
          >


          • 2. AS3: apply() on constructor
            Kiriran Level 1
            yes this was the first thing I tried. The problem is, that "args" will be evaluated as a single parameter, an array. so if you have

            function Foo(a:String, b:String) {
            //
            }

            you get an ArgumentError because it you passed 1 instead of 2 arguments. you can bypass this with apply on normal functions, but not on constructors (or at least I haven't figured that out)