AS3 知道一个函数有多少个参数 [英] AS3 knowing how many arguments a function takes

查看:33
本文介绍了AS3 知道一个函数有多少个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法知道 Flash 中 Function 的实例可以接受多少个参数?了解这些参数是否可选也非常有用.

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.

例如:

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

谢谢

推荐答案

是的:使用 Function.length 属性.我刚刚检查了 docs:似乎没有不过还是要提一下.

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

注意函数名后面没有大括号 ().你需要一个 Function 对象的引用;添加大括号将执行该函数.

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.

编辑

怎么样...rest参数?

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);
}

感谢@felipemaia 指出这一点.

Thanks to @felipemaia for pointing that out.

这篇关于AS3 知道一个函数有多少个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆