Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

deepObjectCopy.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function deepObjectCopy(obj:Object):Object {
	
	if (typeof obj != "object"
	||  object instanceof Button
	||  object instanceof TextField
	||  object instanceof MovieClip) {
	
		// display object (return reference)
		// or non-object value (return value)
		return obj;
	}
	
	var copy;
	
	// define copy object type
	// Boolean, Number, and String objects can be defined
	// as objects with a base value (and can be given properties)
	// class valueOf used to retrieve base value
	if (obj instanceof Boolean) {
		copy = new Boolean(Boolean.prototype.valueOf.call(obj));
	} else if (obj instanceof Number) {
		copy = new Number(Number.prototype.valueOf.call(obj));
	} else if (obj instanceof String) {
		copy = new String(String.prototype.valueOf.call(obj));
		
	// for other objects 
	} else if (obj.__constructor__) {
		
		// if a clone method exists, use that
		if (typeof obj.clone == "function") {
			copy = obj.clone();
			
			// make sure the copy is of the same type
			// in case clone was inherited
			if (copy.__proto__ == obj.__proto__) {
				return copy;
			}
		}
		
		// if no clone or clone was not a valid
		// use object's __constructor__ to create copy
		// if exists; assumes no required parameters
		copy = new obj.__constructor__();
		
	// __constructor__ will not be available for
	// Array and Object instances defined in shorthand
	} else if (obj instanceof Array) {
		copy = [];
	} else {
		copy = {};
	}
	
	// copy object properties
	for (var p in obj) {
		
		// only copy properties unique to object
		// assumes all properties enumerable
		if (obj.hasOwnProperty(p)) {
			
			// deep copy the property being assigned
			copy[p] = arguments.callee(obj[p]);
		}
	}
	
	// return copy
	return copy;
}