如何在ActionScript中重载函数?

时间:2011-09-19 05:09:24

标签: actionscript-3 actionscript overloading

我想要一个能够采用各种类型的功能。 AS3不支持直接重载...所以我不能执行以下操作:

//THIS ISN'T SUPPORTED BY AS3

function someFunction(xx:int, yy:int, someBoolean:Boolean = true){
    //blah blah blah
}
function someFunction(arr:Array, someBoolean:Boolean = true){
    someFunction(arr[0], arr[1], someBoolean);
}

我如何解决它并且仍然有一个能够接受各种类型参数的函数?

2 个答案:

答案 0 :(得分:21)

如果您只想接受任何类型,可以使用*允许任何类型:

function someFunction( xx:*, yy:*, flag:Boolean = true )
{
  if (xx is Number) {
    ...do stuff...
  } else if (xx is String) {
    ...do stuff...
  } else {
    ...do stuff...
  }
}

如果您有大量各种参数,其中顺序不重要,请使用选项对象:

function someFunction( options:Object )
{
  if (options.foo) doFoo();
  if (options.bar) doBar();
  baz = options.baz || 15;
  ...etc...
}

如果您有可变数量的参数,则可以使用... (rest) parameter

function someFunction( ... args)
{
  switch (args.length)
  {
    case 2:
      arr = args[0];
      someBool = args[1];
      xx = arr[0];
      yy = arr[1];
      break;
    case 3:
      xx = args[0];
      yy = args[1];
      someBool = args[2];
      break;
    default:
      throw ...whatever...
  }
  ...do more stuff...
}

对于需要为多个类调用公共函数的情况,应指定每个类共有的接口:

function foo( bar:IBazable, flag:Boolean )
{
  ...do stuff...
  baz = bar.baz()
  ...do more stuff...
}

答案 1 :(得分:2)

可能只有:

function something(...args):void
{
    trace(args[0], args[1]);
}

通过这种方式,您可以轻松地循环遍历您的参数(甚至检查参数类型):

function something(...args):void
{
    for each(var i:Object in args)
    {
        trace(typeof(i) + ": " + i);
    }
}

something("hello", 4, new Sprite()); // string: hello
                                     // number: 4
                                     // object: [object Sprite]