【问题标题】:How to have a default value for ...params function argument?如何为 ...params 函数参数设置默认值?
【发布时间】:2013-01-01 14:56:24
【问题描述】:

我有一些实现这个接口的类:

function execute(entity:Entity, ...params):void;

没关系,不过,我想要这个:

function execute(entity:Entity, ...params = null):void;

因为,不是每个类都需要参数。

它会引发编译错误。

似乎我不能在 AS3 中为 ...params 设置默认值。有什么办法吗?

谢谢。

【问题讨论】:

  • 不能像那样在方法签名中设置默认值,但你可以在函数体中做一些事情,比如params = params || 'defaultVal';
  • 我不喜欢那个解决方案 tbh :p
  • 是否需要指定默认值为null?我相信使用 ... params 调用函数而不实际传递任何额外参数是可以的。

标签: actionscript-3 function parameters default-value


【解决方案1】:

我不知道有什么方法可以在声明时将params 的默认值设置为空数组以外的值,但解决方法如下:

    function exec(entity:Entity, ... extraParams)
    {

        // EDIT: strange that you are getting null, 
        // double check your variable names and if needed you can add:
        if(extraParams == null)
        {
            extraParams = new Array();
        }

        if(extraParams.length == 0) // If none are specified
        {
            // Add default params
            extraParams[0] = "dude";
            extraParams[1] = "man";
        }

        // the rest of the function
    }

【讨论】:

  • 无法访问 null 或未定义参数的成员 length
  • 看看我的编辑是否有帮助,我在上面的代码中添加了一个空检查。还要确保你的变量名在你的实际代码中匹配。
【解决方案2】:
function exec(entity:Entity, ...params){
    // Set default values if no params passed:
    params = arguments.length > 1
                 ? params
                 : {foo:'defaultFooVal', bar:'defaultBarVal'};
    // ...
}

【讨论】:

    猜你喜欢
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    相关资源
    最近更新 更多