How can you overload a function in ActionScript?

2019-04-20 14:54发布

问题:

I want a function to be able to take in various types. AS3 doesn't support overloading directly... so I can't do the following:

//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);
}

How can I work around it and still have a function that is able to take arguments of various types?

回答1:

If you just want to be able to accept any type, you can use * to allow any type:

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

If you have a large number of various parameters where order is unimportant, use an options object:

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

If you have a variable number of parameters, you can use the ... (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...
}

For cases where you need to call a common function to a number of classes, you should specify the interface common to each class:

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


回答2:

Could just have:

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

This way you can easily loop through your arguments and such too (and even check the argument type):

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]