简体   繁体   中英

When does javascript shallow copy vs. deep copy

I have been looking through the stack overflow answers for a while now and have been unable to find a clear, non-contradicting answer to the following question. When does Javascript shallow copy vs deep copy? I have already looked at the popular answers in which case there are 400 answers/comments and everyone seems to be arguing about it. If you know the answer for sure and are an expert, please help us all out. If you have a link on the internet that explains this in total, which I was unable to find, that would be a great help as well. Really appreciate it!

Normally JavaScript doesn't make copies at all. Assigning variables, passing parameters, or returning values don't make copies, they just assign/pass references.

There are some built-in functions that can be used to make copies, such as Array.prototype.slice() and Object.assign() . These only make shallow copies.

I don't think there are any standard JavaScript functions that make deep copies. However, there are functions in libraries like jQuery, lodash, and underscore.js that will do it. For instance, jQuery.extend() is similar to Object.assign() , but it has an optional deep parameter that indicates that it should perform a deep copy.

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