Deep copy and shallow copy of JavaScript

Source: Internet
Author: User
Tags extend shallow copy

There are two types of data in JS:

1. Base type: number, String, Boolean, Null, Undefined

2. Complex Type: Object, Array

deep and shallow copies are only for complex types of data , because the definition of the underlying type data will re-open up new memory.

A shallow copy of the memory address, just add a pointer to the existing memory, when multiple data sharing a memory space; a deep copy is a new pointer and opens up memory space, and the new pointer points to the new memory.

Shallow copy:

var a={
Name: ' Wangjing ',
Sex: ' Woman ',
Age: ' 25 '
};
var b = a ;
B.name = ' white child painting ';
Console.log (A.name); White draw--------------Shallow copy: Copy the memory address, pointer to the same memory space, modify one of the others will also change

Modifying the property value of object B, the property value of object A also changes, this is the shallow copy (the same is the array)

Deep copy:

var c = {}; Do not write Var C; Will error
function Extend (A, b) {
For (Var prop in a) {
B[prop]=a[prop];
}
}
Extend (A,C);
C.name = "Hu";
Console.log (A.name); White draw--------------Deep copy: New memory, new pointer to new memory space modify one of them will not affect the other data

The following code resolves a deep copy

function Extend (A, B) {for (Var prop in a) {//Determine if is the base data type if (typeof a[prop] = = = "Object") {B[prop] = (A[prop].constructor = = = Array)? []: {};//object and array difference processing extend (A[prop], B[prop]);} else {B[prop] = A[prop];}}}

Deep copy and shallow copy of JavaScript

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.