JavaScript deep copy and shallow copy

Source: Internet
Author: User
Tags shallow copy
1. First look at an example:

As can be seen, obj1 copied the value of obj, but only the address reference, modify the value of OBJ1 also affect the value of obj, did not create a new object.

Shallow copy: A value pass on the base data type , and a reference to the reference data type as a transitive copy.

Deep copy: values are passed to the base data type , a new object is created for the reference data type, and its contents are copied

obj2= {
Name: ' Lilei ',
School: ' Hbut ',
Age: {
Age: ' 3 '
},
Run:function AA () {Console.log (this.name)}
}

The property of the parent object is equal to the array or another object, so actually, the child object obtains only one memory address (Obj3.grade===obj2.grade), not the real copy

For the above object, how to implement a deep copy

function Deepcopy (obj) {
temp = Obj.constructor = = = Array? [] : {}
For (let Val in obj) {
Temp[val] = typeof Obj[val] = = ' object '? Deepcopy (Obj[val]): Obj[val]
}
Return Temp
}
Implementing a circular copy of an array or object property in a parent object

2.object.assign (target object, copy source)
In a Vue project that is being done, object.assign is frequently used to achieve copies of images.
When a property in the source target is a direct type, this is a deep copy, which is a shallow copy when the source target has a property of the reference type.


The Obj2 attribute in the example grade object simply refers to a value and does not implement a true copy.

JavaScript deep copy and shallow copy

Related Article

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.