If I have a function like:
public function defaultValues(first = 1,second =2,third = 3)
{
trace(first);
trace(second);
开发者_开发知识库 trace(third);
}
How can I call this function by only passing in a value for second = 20 ?
ActionScript3 does not support named parameters. If you really want this behavior, you can use an associative array... but I don't recommend it unless you really want to be dynamic :
public function defaultValues(params:Object)
{
var first = "first" in params ? params.first : 1;
var second = "second" in params ? params.second : 2;
var third = params.third ? params.third : 3;
trace(first);
trace(second);
trace(third);
}
Then, you can call it:
defaultValues({second: 99});
You should call:
defaultValues(1, 20);
BTW it is extremely bad practice not to use strict typing in ActionScript. Maybe you have Javascript or ActionScript 2 background but it can't be excuse. So your method should looks like:
public function defaultValues(first:int = 1,second:int =2,third:int = 3) : void
{
trace(first);
trace(second);
trace(third);
}
You could have a parameter class for only that function. Although it is a bit of an overkill, it will give you optional parameters which are strictly typed. It does however require a lot more coding.
class DefaultValuesParams {
public var first:int = 1;
public var second:int = 2;
public var third:int = 3;
}
var optionalArgs:DefaultValueParams = new DefaultValueParams();
optinalArgs.second = 20;
defaultValues(optionalArgs);
You may want to overload the method with only one parameter and from the overloaded method call the 3 param method with default values for first and third.
精彩评论