Using Variable Length Arguments With ActionScript
There are times when you simply don't know how many arguments a function will be receiving. Some languages handle this sort of problem with function (or method) overloading-defining a function multiple times with each function definition containing a different number (or type) of parameters. With ActionScript, you can code one function that can dynamically handle different function definitions. Here's how.
Although JavaScript and ActionScript are both ECMAScript languages, they handle variable length arguments fairly differently. JavaScript builds an automatic arguments array as a property of each function; ActionScript requires you to add an explicit notation to your method definition to achieve the same result. Let's look at some code.
public function callMe(… Arguments):void
{
}
You'll see that we include an argument called Arguments, but we prefix it by '...'. This tells ActionScript to expect a variable number of arguments passed to the callMe function. In the example above, these arguments are stored in the 'Arguments' array. We can process these arguments simply by accessing or looping through the array elements:
for (i = 0; i < Arguments.length; i++)
trace (Arguments[i]);
You can combine this notation with standard parameter notation in your function definitions. For example, if you wanted the first argument to be required, and then an unknown number of arguments to be passed in afterwards, you could change the above example to:
public function callMe(FirstArgument:String, … Arguments):void
{
}
You can also determine if an argument is of a certain type by using either the 'instanceof' or 'is' operators like below:
if (Arguments[0] instanceof Sprite)
// do something
Although some might argue that this notation isn't nearly as clean as standard method overloading, it does allow you to achieve the same sort of effect.


0 comments:
Post a Comment