Search code examples
actionscript-3dynamic-class

AS3 Dynamic Class Dynamic Method Names


I'm clearly missing something here.

I need to fill methods of dynamic AS3 class from an array (see silly example below).

But when I call those methods, all of them appear to be the same method. In the example below, all methods are foobar1.

If I create methods by hand, without a loop, everything is fine.

Any clues?

  package foo
  {
    public class Bar
    {
      public function testDynamicClassSanity():void
      {
        var foo:Foo = new Foo();
        var methods:Object = { foobar1: 101, foobar2: 201, foobar3: 301 };

        for (var key:String in methods)
        {
          var val:Number = methods[key];
          foo[key] = function():Number
          {
            return val;
          };
        }

        // Next trace prints
        // 101 = 101 201 = 101 301 = 101
        trace(
            101, "=", foo.foobar1(),
            201, "=", foo.foobar2(),
            301, "=", foo.foobar3()
          );
      }
    }
  }

  internal dynamic class Foo
  {
  };

Solution

  • I would guess the problem is in the scoping of val -- you assume its scope is the for loop, but that is not the case in AS3, the scope is the function. Am I correct that all your calls return 301?

    Update: As working around the issue that you are experiencing (the variable val being referenced and only later resolved instead of being 'copied' into your function) is quite cumbersome: Depending on your use case you could inspect the method calls and just look up the desired result in the table using the functionality provided by Proxy.