Quote:
Originally Posted by felgall
Just to expand on this - it is possible to copy objects in JavaScript but it requires a few more lines of code compared to simply setting up another reference.
The copy is made by creating a new object and then copying the properties and methods across one by one using recursive calls as necessary to work down to elements that can actually be directly accessed rather than just referenced.
|
doesn't always work.
for example:
Code:
var john = new RegExp("hello world")
var jane = deepCopy(john);
jane.name = "Jane Roe";
[jane, john] // ==[ {name : "Jane Roe"}, /hello world/]
for generic objects it works just fine, but if you don't need methods, you can deep copy using native JSON instead of loops:
Code:
jane=JSON.parse(JSON.stringify( john ));
which is much faster than user-land looping and recursive calls.
if you want to take your core to the max, a few minor adjustments are needed to make it more like the structured clone algorithm than JSON.stringify():
Code:
function deepCopy(orig, update) {
var key, val, copy = update || new orig.constructor(orig.valueOf());
for (key in orig) {
val = orig[key];
copy[key] =( val instanceof Object ) ?
deepCopy ( val, val.constructor() ) :
val ;
} /* next */
return copy;
} /* end deepCopy() */
using constructors instead of sniffing types means it works for more than Arrays and generic Objects:
Code:
var john = new RegExp("hello world")
var jane = deepCopy(john);
jane.name = "Jane Roe";
[jane, john]+'' // == [/hello world/,/hello world/]