AS3 knowing how many arguments a function takes

五迷三道 提交于 2020-01-11 06:10:28

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/8256863/as3-knowing-how-many-arguments-a-function-takes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!