Possible Duplicate:
What is the most efficient way to clone a JavaScript object?
How to clone js object with out reference like these:
{ ID: _docEl,
Index: next,
DocName: _el
}
Any ideas?
Possible Duplicate:
What is the most efficient way to clone a JavaScript object?
How to clone js object with out reference like these:
{ ID: _docEl,
Index: next,
DocName: _el
}
Any ideas?
You'll have to iterate over the object and make copies of all its properties.
And then if any of its properties are also objects, assuming you want to clone those too, you'll have to recurse into them.
There's various methods for doing this here: What is the most efficient way to clone a JavaScript object?
Here's how I'd do it, based on thomasrutter's suggestion (untested code):
function cloneObj(obj) {
var clone = {};
for (var i in obj) {
if (obj[i] && typeof obj[i] == 'object') {
clone[i] = cloneObj(obj[i]);
} else {
clone[i] = obj[i];
}
}
return clone;
}
You can use jQuery.extend:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
The following post is so helpful:
What is the most efficient way to deep clone an object in JavaScript?
JavaScript JS object clone
Object._clone = function(obj) {
var clone, property, value;
if (!obj || typeof obj !== 'object') {
return obj;
}
clone = typeof obj.pop === 'function' ? [] : {};
clone.__proto__ = obj.__proto__;
for (property in obj) {
if (obj.hasOwnProperty(property)) {
value = obj.property;
if (value && typeof value === 'object') {
clone[property] = Object._clone(value);
} else {
clone[property] = obj[property];
}
}
}
return clone;
};
CoffeeScript JS object clone
# Object clone
Object._clone = (obj) ->
return obj if not obj or typeof(obj) isnt 'object'
clone = if typeof(obj.pop) is 'function' then [] else {}
# deprecated, but need for instanceof method
clone.__proto__ = obj.__proto__
for property of obj
if obj.hasOwnProperty property
# clone properties
value = obj.property
if value and typeof(value) is 'object'
clone[property] = Object._clone(value)
else
clone[property] = obj[property]
clone
Now you can try to do that
A = new TestKlass
B = Object._clone(A)
B instanceof TestKlass => true
function objToClone(obj){
return (new Function("return " + obj))
}