你怎么可以重载在ActionScript函数?你怎么、函数、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...

我想的函数,以便能够采取各种类型。 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...
}

如果你有一个可变数量的参数,你可以使用... (其余的)参数:

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...
}
阅读全文

相关推荐

最新文章