It is difficult to understand these concepts, especially in the shades of a copy. Here is an inappropriate example to understand, shallow copy is twins, deep copy is to clone themselves alone.
First, data type classification:
Second, what is called the pointer pointing
Stack memory, heap memory, pointer pointing (red circle slash below).
Three, assignment, copy, reference difference?
- assignment refers to a value
一个变量赋予某个值,包含两种方式,一种是直接量,另一种,是将另一个变量的值传递给这个变量。拷贝和引用都属于后者
.
- The purpose of the reference is
将指针指向相同堆内存中的某一位置
.
- The purpose of the copy is
改变指针的指向,并且内部属性或者元素的值相等
. The underlying data type changes the pointer point in the assignment process, so it is usually said 基础类型的引用只存在只读状态
. A pointer to a complex data type contains two pointers to the stack memory, and the pointer to the heap memory, which simply assigns a value, but the latter is not so easy.
var= { name:‘lc‘, friends: [‘xm‘,‘xm‘,‘xl‘]}
From this code, we know very well that person.name
person.friends
each element in the pointer to the stack memory, person
and person.friends
the pointer to the heap memory, thus we can draw two points:
- A pointer to a copy that alters a complex data type must first change the pointer to the heap memory , such as a pointer to the point
person
.
- The copy changes the pointer direction, can be changed only
person
pointer to, this kind is called shallow copy (shallow copy), can also change person
, and person.friends
so on all pointers point, this kind is commonly called deep copy (deep copy).
Four, shallow copy and deep copy
In the above, I have described the shallow copy and deep copy, here again rigorous summary: shallow copy only changes in the complex data type of the pointer points, that is not completely changed; deep copy of the head completely change all the pointer point, that is, completely changed .
Shallow copy
For example, the above example code:
var shallow_copy={};for(varin{ = person[i];}
or ES6.Object.assign()
Deep copy
The implementation of the method is also a variety, can be broadly divided into two categories: one is JSON, the other is recursive loop traversal assignment.
One of the most common is in jquery $.extend()
.
Other
Understanding these, such as the difference between the Const,es6 module and the Commonjs module in the ES6 syntax, becomes very well understood.
This article is a reference to a number of articles, and their own conclusions, if anything wrong, please forgive and point out.
such as how to verify the shallow copy to change part of the pointer pointing, deep copy of the specific implementation of the problem, you can also refer to the following documents:
Document 1
Document 2
Document 3
[Source demo, to be continued ...] ]
Javascript object Copy (deep copy)