习惯了C++和Java的语法,以为ActionScript3也同样支持函数重载,昨天试着写了下面这样一个类后发现居然报错:Multiple constructor definitions found,原来ActionScript3并不支持我们常用的那种函数重载方式。
public class MyClass
{
private var name:String = "" ;
public function MyClass()
{
}
public function MyClass(str:String)
{
this .name = str;
}
public function get Name():String
{
return this .name;
}
}
{
private var name:String = "" ;
public function MyClass()
{
}
public function MyClass(str:String)
{
this .name = str;
}
public function get Name():String
{
return this .name;
}
}
那么在ActionScript3里是如何实现这样的功能的呢?其实是借鉴c语言里的可变参数列表来实现的,脚本语言好像都是这么做的,如下所示:
public class MyClass
{
private var name:String = "" ;
public function MyClass( arg)
{
if (arg.length == 0 )
{
this .name = " default " ;
}
else if (arg.length == 1 )
{
this .name = arg[ 0 ];
}
}
public function get Name():String
{
return this .name;
}
}
{
private var name:String = "" ;
public function MyClass( arg)
{
if (arg.length == 0 )
{
this .name = " default " ;
}
else if (arg.length == 1 )
{
this .name = arg[ 0 ];
}
}
public function get Name():String
{
return this .name;
}
}
我们自己先规定好可接受的参数列表,然后去做相应的处理。但缺点是很明显的,没有编译时的参数检查,出错的概率增大。不过毕竟不是强类型语言,不能要求这么严格的。调用时就可以如下所示:
public
function
init():
void
{
var c1:MyClass = new MyClass();
Alert.show(c1.Name, " info " );
var c2:MyClass = new MyClass( " hello " );
Alert.show(c2.Name, " info " );
}
{
var c1:MyClass = new MyClass();
Alert.show(c1.Name, " info " );
var c2:MyClass = new MyClass( " hello " );
Alert.show(c2.Name, " info " );
}