简体   繁体   中英

Which JavaScript objects don't Deep Clone by default?

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?

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM