2013-01-17 108 views
0

我有一些类实现这个接口:如何为... params函数参数设置默认值?

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

这是确定的,但是,我想有这样的:

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

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

它引发编译错误。

似乎我不能有AS3默认值... params。有没有办法做到这一点?

谢谢。

+1

灿在方法签名中没有像这样设置默认值,但是你可以在函数体中做一些事情,比如'params = params || 'defaultVal';' – Madbreaks

+0

我不是那种解决方案的粉丝tbh:p – Artemix

+1

你需要指定一个默认值null吗?我相信在没有实际传递任何额外参数的情况下用... params调用函数是很好的。 –

回答

3

我不知道的任何方式来设置的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 
    } 
+0

无法访问空值或未定义参数的成员'length' – Madbreaks

+0

看看我的编辑是否有帮助,我在上面的代码中添加了空检查。同时确保您的变量名称与您的实际代码相匹配。 – ToddBFisher

0
function exec(entity:Entity, ...params){ 
    // Set default values if no params passed: 
    params = arguments.length > 1 
       ? params 
       : {foo:'defaultFooVal', bar:'defaultBarVal'}; 
    // ... 
} 
相关问题