Tutorial :Which JavaScript objects don't Deep Clone by default?



Question:

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?


Solution:1

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


Solution:2

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?


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »