Possible Duplicate:
Copying an Object in Javascript
How can I create a new object from other object? Something like copy constructor in other languages like C#.
Possible Duplicate:
Copying an Object in Javascript
How can I create a new object from other object? Something like copy constructor in other languages like C#.
There is no built-in framework for copying in JS. Many of the simple types are immutable value types which you can just copy the references of. Array and Object you can write a function to copy for you, eg.:
function copy(o, isdeep) {
if (o===undefined || o===null || ['string', 'number', 'boolean'].indexOf(typeof o)!==-1)
return o;
var n= o instanceof Array? [] : {};
for (var k in o)
if (o.hasOwnProperty(k))
n[k]= isdeep? copy(o[k], isdeep) : o[k];
return n;
}
However for every other type of object you will have to write your own copy code. Many built-in objects are inherently uncopiable.
//
function copycat(obj){
if(!obj.constructor) return obj;
var cop= new obj.constructor;
for(var p in obj){
if(obj.hasOwnProperty(p)){
cop[p]= obj[p];
}
}
return cop;
}
var a= [1, 2, 3, 4, 5];
var o={x:100,y:100,z:100};
var b=copycat(a);
var o2=copycat(o);