可能重复:
What is the most efficient way to clone a JavaScript object?
如何使用以下引用来克隆js对象:
{ ID: _docEl,
Index: next,
DocName: _el
}
有什么想法吗?
答案 0 :(得分:9)
您必须遍历该对象并复制其所有属性。
然后,如果它的任何属性也是对象,假设你想要克隆它们,你将不得不递归到它们。
这里有各种方法: What is the most efficient way to clone a JavaScript object?
答案 1 :(得分:6)
基于thomasrutter's suggestion(未经测试的代码),我就是这样做的:
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;
}
答案 2 :(得分:5)
您可以使用jQuery.extend:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
以下帖子非常有帮助:
What is the most efficient way to deep clone an object in JavaScript?
答案 3 :(得分:2)
JavaScript JS对象克隆
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 = (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
现在你可以尝试这样做
A = new TestKlass
B = Object._clone(A)
B instanceof TestKlass => true
答案 4 :(得分:1)
function objToClone(obj){
return (new Function("return " + obj))
}