Object.assign () {... obj} JSON. The difference between several copies of Parse, etc.

Source: Internet
Author: User

Let obj = {age:10}
Let obj1 = {grade:1, name: {first: ' Bob '}}
Let Objs = Obj1let Obja = object.assign (obj, obj1) Let OBJJ = Json.parse (json.stringify (obj1)) Let OBJK = {... obj1}
Console.log (Obja) console.log (OBJJ) console.log (OBJK)
Obj1.grade = 9obj1.name.first = ' Chris '
Console.log (OBJS) console.log (obja) console.log (OBJJ) console.log (OBJK) printing results:

{age:10, grade:1, name: {first: ' Bob '}}

{grade:1, Name: {first: ' Bob '}}

{grade:1, Name: {first: ' Bob '}}

{grade:9, Name: {first: ' Chris '}}

{age:10, grade:1, name: {first: ' Chris '}}

{grade:1, Name: {first: ' Bob '}}

{grade:1, Name: {first: ' Chris '}}

Conclusion: Because the object creates a variable on the stack on the heap to save its address, it is also called a pointer variable

Shallow copy such as let simpleobj = obj;

Then only the pointer variable of obj on the stack is copied to simpleobj that is, simpleobj the actual stored value is the memory address of the Obj object that points to the same heap memory address as obj, so changing the value of obj simpleobj will change

A deep copy is a copy of an object placed in another heap before the memory address changes the object will not have any effect on the copied object

There are several deep-copy methods in JS

Object.assign () Not deep copy or shallow copy first-level copy if the inner layer has a reference type, it's a shallow copy.

... Expansion is the same as assign

Json.parse (JSON. Stringify ()) deep copy but the disadvantage is that you can't copy the constructor method solution is recursion

Object.assign () {... obj} JSON. The difference between several copies of Parse, etc.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.