Wednesday, October 22, 2008

deepcopy




deepObjectCopy.as

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;
}