Discussion on Object oriented Deep Copy and Shallow Copy in JavaScript

  • 2021-07-06 09:56:51
  • OfStack

Before understanding deep copy and shallow copy, we need to understand some basic concepts. Variable types stored in memory are divided into value types and reference types.

1. The storage characteristics of value type assignment, which copies all the data in the variable and stores it to the new variable.

For example: var num = 123; var num1=num;

Indicates that the number stored in the variable is 123. Then copy 1 copy of the data, that is, copy 1 copy of 123. Then there are 2 arrays in the memory; Assigning copy data to num2 is characterized by having two copies of data in memory. This can be understood as shallow copy.

2. Assignment of reference types.

var o = {name: 'Zhang 3'};

var obj=o;

Assignment is to make a copy of the data stored in the variable o, and then assign the data to obj. There is 1 point of data in memory, and the name property modified by obj will affect name in o.

If all the reference structures of the data are copied 1 copy when copying, then the data is a deep copy independently in memory;

If the copy, only for the current object of the attribute copy, and the attribute is the reference type this does not consider, then is shallow copy;

Copy: 1 copy. Refers to copying object data;

When discussing deep copying and shallow copying, 1 must ensure that the attributes of objects are also reference types.

Related articles: