God*_*her 4 flash function introspection actionscript-3
有没有办法知道Function的一个实例可以在Flash中使用多少个参数?了解这些参数是否可选也是非常有用的.
例如 :
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
Run Code Online (Sandbox Code Playgroud)
谢谢
RIA*_*tar 13
是的:使用Function.length属性.我刚检查了文档:虽然它似乎没有被提及.
trace(foo.length); //0
trace(bar.length); //2
trace(jad.length); //2
Run Code Online (Sandbox Code Playgroud)
请注意,函数名后面没有大括号().您需要Function对象的引用; 添加大括号将执行该功能.
我不知道如何确定其中一个参数是可选的.
编辑
怎么样......休息参数?
function foo(...rest) {}
function bar(parameter0, parameter1, ...rest) {}
trace(foo.length); //0
trace(bar.length); //2
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为无法知道将传递多少个参数.请注意,在函数体内,您可以确切地知道传递了多少个参数,如下所示:
function foo(...rest) {
trace(rest.length);
}
Run Code Online (Sandbox Code Playgroud)
感谢@felipemaia指出这一点.