as3: using an object to pass arguments in any order - class configuration
I want to pass through configuration arguments to a class. These are all th开发者_StackOverflow社区e 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.
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 casethis['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.
精彩评论