Wednesday, January 28, 2015
Creating Optional Parameters in AS3
function greetPerson(greeting:String = "Hello", firstName:String = "John"):void
{
trace(greeting + " " + firstName);
}
greetPerson();
greetPerson("Hi","Susan");
If you call this function without passing any arguments, then the default values assigned to the parameters will be used. If you pass arguments, then these arguments will replace the default values.
If your parameters have no default values, then they become required parameters. This means that you must pass arguments to them whenever you call the function.
function greetPerson(greeting:String, firstName:String):void
{
trace(greeting + " " + firstName);
}
greetPerson();
// This function call will result in an error.
// Since the function parameters have no default values,
// arguments must be passed to them.
// Not passing any arguments to a function
// with required parameters will result in an error.
If you want to make some parameters required while making the other parameters optional, the required parameters must be defined first. The optional parameters should only be defined at the end of the parameter list, after all of the required parameters have been defined.
In the example below, the first two parameters have no default values assigned to them so this makes them both required parameters. And then a third optional parameter is added only after the first two required parameters have been defined.
function greetPerson(greeting:String, firstName:String, lastName:String = "Doe"):void
{
trace(greeting + " " + firstName + " " + lastName);
}
greetPerson("Hello","John");
If we placed the optional parameter at the beginning of this functions parameter list instead, then this would have resulted in an error.
Labels:
as3,
creating,
in,
optional,
parameters
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.