views:

59

answers:

2

There's a lot of hubub about "cloning" JavaScript objects. However, as I understand it, it's a simple matter:

function clone(obj) {
    return obj;
}

Now I realize that DOM objects aren't cloned this way, but as I understand it the DOM is part of the browser, not part of JavaScript.

What objects require deep-cloning and why?

+4  A: 

That just returns a reference to the exact same object. It doesn't clone anything.

x = {}, 
c=function(o){return o}, 
y = c(x), 
result = (x === y)

result is true

meder
I suppose I should know better. For some reason I thought it was copy-on-write, but I guess that's only for primitive values.
CoolAJ86
+1  A: 

This is in some respects a pass/assign by reference vs by value debate. By reference tends to be the default in most languages for anything that isn't a primitive for a number of reasons, probably chief amongst which are:

1) You're likely to churn through a lot of memory if each assignment / pass to a function creates a deep copy.

2) Extra fun when you're trying change the state of things... no more this.x = 5 if this.x is already bound. Probably something like this = this.clone({x: 5}) instead, if we were semi-lucky.

For more background, take a look at these two links:

http://oranlooney.com/functional-javascript/

http://oranlooney.com/deep-copy-javascript/

I think the real question should probably be -- why isn't there a nice convenient method of Object provided for doing deep copies?

Weston C
Doing deep copy correctly can be *hard* - think about handling circular references, private members, etc.
Matt Ball
All the more reason it should be implemented in the language rather than left up to the sorry lot using it. ;)
Weston C