3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

オブジェクトの複製

Last updated at Posted at 2012-07-20

AS3だとめんどくさいディープコピーの作成。

完全なディープコピーは無理そうなので、以下の条件で妥協。

■プリミティブ型、clone関数をもつ型(Matrix,Pointなど)、ByteArray型、およびこれらによって形成されるArray,Vector,Dictionary型のオブジェクトの複製を返す。
■その他は浅いコピー

clone.as
static public function clone(source:*):*{
	var name:String = getQualifiedClassName(source);
	var o:*;
	var classDef:Class;
	var cloneFunction:Function;
	if( name == "Object" || name == "Array" || source is Vector.<*> || name == "flash.utils::Dictionary" ){
		classDef = getDefinitionByName(name) as Class;
		o = new classDef();
		
		var flag:Boolean = false; 
		for( var s:Object in source ){
			o[s] = clone( source[s] );
			flag = true;
		}
		return o;
	}else if( name == "flash.utils::ByteArray" ){
		classDef = getDefinitionByName(name) as Class;
		o = new classDef();
		var p:uint = source.position;
		source.position = 0;
		source.readBytes(o, 0, source.length);
		source.position = p;
		return o;
	}else if( source is Object && source.hasOwnProperty("clone") && (cloneFunction = source.clone) is Function && cloneFunction.length == 0 ){        
		return source.clone();
	}
	return source;
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?