【问题标题】:AS3 knowing how many arguments a function takesAS3 知道一个函数需要多少个参数
【发布时间】:2012-01-05 14:40:09
【问题描述】:

有没有办法知道一个 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

谢谢

【问题讨论】:

    标签: flash actionscript-3 function introspection


    【解决方案1】:

    是的,有:使用 Function.length 属性。 我刚刚检查了docs:不过那里似乎没有提到它。

    trace(foo.length); //0
    trace(bar.length); //2
    trace(jad.length); //2
    

    请注意,函数名后面没有大括号 ()。您需要 Function 对象的引用;添加大括号将执行该函数。

    我不知道如何确定其中一个参数是可选的。

    编辑

    ...rest parameters 呢?

    function foo(...rest) {}
    function bar(parameter0, parameter1, ...rest) {}
    
    trace(foo.length); //0
    trace(bar.length); //2
    

    这是有道理的,因为无法知道将传递多少个参数。 请注意,在函数体中,您可以确切知道传递了多少个参数,如下所示:

    function foo(...rest) {
        trace(rest.length);
    }
    

    感谢@felipemaia 指出这一点。

    【讨论】:

    • function foo(... args) 的行为会是什么?
    • 显然它返回 0,无论您是否实际传递参数。我会编辑我的答案。感谢您指出这种情况。
    • 投反对票的人能否澄清一下他认为这个答案有什么问题?也忍不住注意到this answer 大致同时被否决...
    • +1。哇。以前从未见过这个。是不是来自 AS2 的 Object.length 潜入了 AS3:)?
    猜你喜欢
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 2022-12-03
    相关资源
    最近更新 更多