views:

206

answers:

1

I want to pass through configuration arguments to a class. These are all the optional vars that go into configuring the class - and should be able to run in any order.

at the moment i just pass through the optional vars the regular way. Supposing the constuctor was like the following:

private var _reqVar:String;
private var _optVar1:String;
private var _optVar2:String;

public function Constructor(reqVar:String, optVar1:String = "empty", optVar2:String = "empty){

    // set the variable to equal the arguments here...

} 

the problem with this is for the end user, where instantiating the class isnt particularly readable (especially when the argument list can grow quite large)

ideally i would like to pass the arguments though similar to this:

var instance:ClassType = new ClassType(reqVar, {width:100, height:100, speed:4, lives:3})

which again is fairly straight forward. where i stumble over are the following points:

  • assigning the argument to the var of the same key (i know in php to reference a variable name from a key you can use $$key = $value, is there an equivalent in as3?)
  • display an error (using the 'throw' method) for variable names not supported by the class

any help appreciated.

+1  A: 

Updated answer:

public function Test(reqVar, optionalVars:Object)
{
    for (var prop:String in optionalVars)
    {
        try
        {
            this[prop] = optionalVars[prop];
        }
        catch (error:Error)
        {
            throw new Error("Unknown property: " + prop);
        }
    }

}

So the answers to your questions are:

  • You assign to a property or variable by name using object[NAME], in this case this['propertyName'].
  • You can check whether a property exists using hasOwnProperty. Update: If you also want to assign to variable other than properties, I don't think you can check if they exist. To solve this, you could either just assume they exist, assign to them and get an error when you use an invalid variable name. You could also wrap the assignment in a try ... catch block and throw a prettier exception as I've shown above.
TC
Gold Star for you good sir! Thanks a bunch.
Beans
I just marked this as unanswered as i have one more question - this doesn't seem to be able to set the values it the vars are declared as private - as soon as i declare them as public it works fine. is this to be expected? Obviously i would like to keep them private if possible to control the integrity of the values.
Beans
Good point Beans. I'm new to AS3 myself and hadn't realized that hasOwnProperty is limited to properties, as the name sort of implies :) Updated my answer so that it should now work with any variable.
TC
Perfect, I ended up with a near identical solution to that - your original answer was the catalyst to my solution, many thanks!
Beans