你怎么可以重载在ActionScript函数? [英] How can you overload a function in ActionScript?

查看:208
本文介绍了你怎么可以重载在ActionScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想的函数,以便能够采取各种类型。 AS3不支持直接超载......所以我不能做到以下几点:

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?

推荐答案

如果你只是想能够接受任何类型的,你可以使用 * 来允许任何类型

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

如果你有一个可变数量的参数,你可以使用<一个href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6#..._%28rest%29_parameter"><$c$c>... (其余的)参数:

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

这篇关于你怎么可以重载在ActionScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆