Is there a way to know how many arguments an instance of Function can take in Flash? It would also be very useful to know if these arguments are optional or not.
For example :
public function foo() : void //would have 0 arguments
public function bar(arg1 : Boolean, arg2 : int) : void //would have 2 arguments
public function jad(arg1 : Boolean, arg2 : int = 0) : void //would have 2 arguments with 1 being optional
Thanks
Yes there is: use the Function.length property. I just checked the docs: it doesn't seem to be mentioned there though.
trace(foo.length); //0
trace(bar.length); //2
trace(jad.length); //2
Notice there are no braces () after the function name. You need a reference of the Function object; adding the braces would execute the function.
I do not know of a way to ascertain that one of the arguments is optional though.
EDIT
What about ...rest parameters?
function foo(...rest) {}
function bar(parameter0, parameter1, ...rest) {}
trace(foo.length); //0
trace(bar.length); //2
This makes sense since there is no way of knowing how many arguments will be passed. Note that within the function body you can know exactly how many arguments were passed, like so:
function foo(...rest) {
trace(rest.length);
}
Thanks to @felipemaia for pointing that out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With