Wednesday, November 30, 2011

Creating Optional Parameters in AS3

When a function has parameters, you don't always need to pass arguments to them. You can create parameters that are optional. To make a parameter optional, assign a value to it when it is created. This value will become the parameter's default value - the value that will be used when no argument is passed to it. Below is an example:

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 function's parameter list instead, then this would have resulted in an error.

No comments:

Post a Comment