今天同事问我有as3中对象深度拷贝的问题
原来还真是没用过,今天google后自己总结下,便于大家参考
as3中通过ByteArray可以进行对象的深度拷贝
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
import flash.net.*;
import src.*;
function cloneObject(source:Object) :* {
var typeName:String = getQualifiedClassName(source);//获取全名
trace(”输出类的结构”+typeName);
//return;
var packageName:String = typeName.split(”::”)[0];//切出包名
trace(”类的名称”+packageName);
var type:Class = getDefinitionByName(typeName) as Class;//获取Class
trace(type);
registerClassAlias(packageName, type);//注册Class
//复制对象
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return copier.readObject();
}
有的人说用复制对象那一段不就可以了吗,但是实际上行不通
对于数组深度复制来说, 复制对象的后面4句代码就足够了
var a1:Array=[1,2,3];
var a2:Array =cloneObject(a1);
var a3:Array = a1;
a1.push(”youmila”);
trace(”a1:”+a1+”a2:”+a2+”a3″+a3);
但是对于对象来说肯定不行
用列子测试下
src.youmila.as 代码:
package src{
public class youmila{
private var $_name:String =”youmila”;
private var $_num:Number =0;
public function youmila():void{
trace($_name);
}
public function secondFunc():void{
$_num++;
trace(”this a called function $_num::”+$_num);
}
}
}
yapollo.as 代码:
package {
public class yapollo{
private var $_name:String =”yapollo”;
public var $_num:Number =0;
public function yapollo():void{
trace($_name);
}
public function secondFunc():void{
$_num++;
trace(”this a called function $_num::”+$_num);
}
}
}
测试实例
var uml1:youmila = new youmila();
var uml2 = cloneObject(uml1);
trace(”类型”+getQualifiedClassName(uml2));
输出结果:
youmila
类型Object
原来的对象类型丢失了,所以对于对象而言,四行不够,必须
用registerClassAlias来保存类的别名,以用于丢失后恢复类的类型
测试实例
var uml1:youmila = new youmila();
var uml2 = cloneObject(uml1);
trace(”类型”+getQualifiedClassName(uml2));
var apollo:yapollo = new yapollo();
apollo.secondFunc();
var apollo2 = cloneObject(apollo);
trace(”第一次输出复制对象的$_num值”+apollo2.$_num);
trace(”类型”+getQualifiedClassName(apollo2));
apollo2.secondFunc();
trace(”第二次输出复制对象的$_num值”+apollo2.$_num);
输出结果:
youmila
输出类的结构src::youmila
类的名称src
[class youmila]
youmila
类型src::youmila
yapollo
this a called function $_num::1
输出类的结构yapollo
类的名称yapollo
[class yapollo]
yapollo
第一次输出复制对象的$_num值1
类型yapollo
this a called function $_num::2
第二次输出复制对象的$_num值2