简体   繁体   English

…params函数参数如何具有默认值?

[英]How to have a default value for …params function argument?

I have some classes that implement this interface: 我有一些实现此接口的类:

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

It's ok, however, I'd like to have this: 可以,但是,我想要这样:

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

because, not every class needs params. 因为,并非每个班级都需要参数。

It throws a compilation error. 它将引发编译错误。

Seems like I cant have a default value for ...params in AS3. 似乎我无法为AS3中的... params设置默认值。 Is there any way to do that? 有什么办法吗?

Thanks. 谢谢。

I am not aware of any way to set the default value of params to something other than an empty array at the point of declaration, but a work around would be something like: 我不知道有什么方法可以在声明时将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
    }
function exec(entity:Entity, ...params){
    // Set default values if no params passed:
    params = arguments.length > 1
                 ? params
                 : {foo:'defaultFooVal', bar:'defaultBarVal'};
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM