My function for cloning looks like this: It covers objects, arrays,
functions and jQuery objects / custom objects with an own clone() function:
------------------------------------------------------------------------------------------------------------------------------------------------------
$.extend({
clone: function(obj, deep) {
// Clone a jQuery object / objects with a custom clone function
if (obj && obj && obj.clone && $.isFunction(obj.clone)) {
return obj.clone(deep);
}
// Clone a function
if ($.isFunction(obj)) {
return function() {return obj.apply(this, arguments);};
}
if (obj && obj.constructor == Array) {
// Clone an array
var clone = [];
for(var i = 0; i < obj.length; i++) {
clone[i] = (deep == true)
? obj[i]
: $.clone(obj[i], deep);
}
return clone;
} else if (obj && obj.constructor == Object) {
// Clone an object
var clone = {};
for (var p in obj) {
clone[p] = (deep == true)
? obj[p]
: $.clone(obj[p], deep);
}
}
return clone;
}
------------------------------------------------------------------------------------------------------------------------------------------------------
I'm interested to hear feedback,
-- Felix
--------------------------
My Blog: http://www.thinkingphp.org
My Business: http://www.fg-webdesign.de
Erik Beeson wrote:
Thanks for sharing this. I'm pretty sure what you suggest won't
properly deal with arrays. Objects aren't the same as arrays. Here's
how I do something like that:
function deepCopy(obj) {
if(obj && obj.constructor == Object) {
var newObj = new Object();
for(var field in obj) {
newObj[field] = deepCopy(obj[field]);
}
return newObj;
} else if(obj && obj.constructor == Array) {
var newArray = new Array();
for(var i = 0; i < obj.length; i++) {
newArray[i] = deepCopy(obj[i]);
}
return newArray;
}
return obj;
}
Also, while it's fine to use $ however you want in your own code, for
code that you're making public, I suggest you checkout the plugin
authoring guide about not using $ directly:
http://docs.jquery.com/Plugins/Authoring#Custom_Alias
--Erik
On 8/5/07, *weepy * <[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>>
wrote:
During assingment, if the object is not primative, Javascript will
return a pointer to the object rather than a copy.
E.g.
a = [1,2]
b = a
b[0]=3
a ==> [3,2]
This clone function makes it possible to copy an object.
$.clone = function (obj) {
if(typeof(obj) != 'object') return obj;
if(obj == null) return obj;
var newobj = new Object();
for(var i in obj)
newobj[i] = $.clone(obj[i]);
return newobj;
}
a = [1,2]
b = $.clone(a)
b[0]=3
a ==> [1,2]
I have found this function invaluable when comparing and complex
Javascript objects.