0

I like finding out about tricky new ways to do things. Let's say you've got a class with a property that gets set to the value of an argument in the constructor, like so:

package{
 public class SomeClass{
  private var someProperty:*;
  public function SomeClass(_someProperty:*):void{
   someProperty = _someProperty;
  }
 }
}

That's not exactly a hassle. But imagine you've got... I don't know, five properties. Ten properties, maybe. Rather then writing out each individual assignment, line by line, isn't there a way to loop through the constructor's arguments and set the value of each corresponding property on the new instance accordingly? I don't think that the ...rest or arguments objects will work, since they only keep an enumerated list of the arguments, not the argument names - I'm thinking something like this would be better:

for(var propertyName:String in argsAsAssocArray){this[propertyName] = argsAsAssocArray[propertyName];}

... does something like this exist?

1
  • It should be noted that the reason there's no built in way to do things like this is that (besides a few things like movieclips) objects don't have "names" in any real sense. If you define myFunction(str:String), then you get passed in a reference to a String, and that reference happens to be called "str", but the name "str" is not in any way a property of the String object in question. Hence if you use myFunction(..rest), then the objects that get passed in have no names at all! Commented Apr 9, 2010 at 12:37

2 Answers 2

1

No, there isn't. Here's what I use though:

class A {
    private var arg1:Type1;
    private var arg2:Type2;
    private var arg3:Type3;
    private var arg4:Type4;
    private static const PARAMS:Array = "arg1,arg2,arg3,arg4".split(",");
    public function A(arg1:Type1, arg2:Type2, arg3:Type3, arg4:Type4) {
        var i:uint = 0;
        for each (var name:String in PARAMS) this[name] = arguments[i++];
    }
}

You may want to check out Haxe. It has many advantages over AS3 and provides a solution even to this problem, using rtti, which unlike AS3 rtti also contains method parameter names.

Sign up to request clarification or add additional context in comments.

1 Comment

it's just not possible, eh? I was kind of afraid of that. Oh well.
0

Using the reflection class describeType probably provides the most interesting information regarding the arguments, still unfortunately the property names aren't there either.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.