简体   繁体   中英

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. 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:

    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'};
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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