Update: Thank you for your support. Recently, a blog official website came out to facilitate your system reading. There will be more content and more optimization in the future

—— The following is the text ——

Assignment (Copy)

Assignment is the process of assigning a value or object to a variable, divided into the following two parts

  • Basic data type: assignment, after which the two variables do not affect each other
  • Reference data type: An assignment in which two variables have the same reference to the same object and affect each other

Assign to a primitive type. The two variables do not affect each other.

/ / wooden Yi Yang
let a = "muyiy";
let b = a;
console.log(b);
// muyiy

a = "change";
console.log(a);
// change
console.log(b);
// muyiy
Copy the code

When a reference type is assigned, two variables refer to the same object. Changing variable A affects variable B, even if it only changes the basic type data in object A.

/ / wooden Yi Yang
let a = {
    name: "muyiy".book: {
        title: "You Don't Know JS".price: "45"}}let b = a;
console.log(b);
/ / {
// name: "muyiy",
// book: {title: "You Don't Know JS", price: "45"}
// } 

a.name = "change";
a.book.price = "55";
console.log(a);
/ / {
// name: "change",
// book: {title: "You Don't Know JS", price: "55"}
// } 

console.log(b);
/ / {
// name: "change",
// book: {title: "You Don't Know JS", price: "55"}
// } 
Copy the code

Shallow and deep copies are often used when you don’t want to change variable A to affect variable B during development.

Shallow Copy

1. What is shallow copy

Creates a new object with an exact copy of the original object property values. If the property is a primitive type, it copies the value of the primitive type, and if the property is a reference type, it copies the memory address, so if one object changes the address, it affects the other object.

In the figure above, the SourceObject is the original object, which contains the base type attribute field1 and the reference type attribute refObj. After a shallow copy, the field2 and filed1 properties are different and do not affect each other. But the reference type refObj is still the same, and changing it will affect another object.

A shallow copy only solves the problem of the first layer, copying the first base type value and the reference type address of the first layer.

2. Shallow copy application scenarios

  • Object.assign()

The object.assign () method is used to copy the values of all enumerable properties from one or more source objects to target objects. It will return the target object.

Some articles say object.assign () is a deep copy, which is not true.

/ / wooden Yi Yang
let a = {
    name: "muyiy".book: {
        title: "You Don't Know JS".price: "45"}}let b = Object.assign({}, a);
console.log(b);
/ / {
// name: "muyiy",
// book: {title: "You Don't Know JS", price: "45"}
// } 

a.name = "change";
a.book.price = "55";
console.log(a);
/ / {
// name: "change",
// book: {title: "You Don't Know JS", price: "55"}
// } 

console.log(b);
/ / {
// name: "muyiy",
// book: {title: "You Don't Know JS", price: "55"}
// } 
Copy the code

After the above code changes object A, the basic properties of object B remain the same. But when you change the object Book in object A, the corresponding position of object B also changes.

  • A grammarSpread
/ / wooden Yi Yang
let a = {
    name: "muyiy".book: {
        title: "You Don't Know JS".price: "45"}}letb = {... a};console.log(b);
/ / {
// name: "muyiy",
// book: {title: "You Don't Know JS", price: "45"}
// } 

a.name = "change";
a.book.price = "55";
console.log(a);
/ / {
// name: "change",
// book: {title: "You Don't Know JS", price: "55"}
// } 

console.log(b);
/ / {
// name: "muyiy",
// book: {title: "You Don't Know JS", price: "55"}
// } 
Copy the code

The code shows that the actual effect is the same as object.assign ().

  • Array.prototype.slice()

The slice() method returns a new array object that is a shallow copy of the original array determined by begin and end (not including end). The original array will not be changed.

/ / wooden Yi Yang
let a = [0."1"[2.3]].let b = a.slice(1);
console.log(b);
/ / [" 1 ", [2, 3]]

a[1] = "99";
a[2] [0] = 4;
console.log(a);
// [0, "99", [4, 3]]

console.log(b);
/ / [" 1 ", [4, 3]]
Copy the code

It can be seen that the value of B [0] does not change after a[1] is changed, but the corresponding value of B [1][0] also changes after a[2][0] is changed. Note The slice() method is a shallow copy, corresponding to concat, etc., in the face of complex array structure should pay extra attention to.

Deep Copy

1. What is deep copy

Deep copy copies all attributes and dynamically allocated memory to which the attributes point. Deep copy occurs when an object is copied along with the object it references. Deep copy is slower and more expensive than shallow copy. The two objects do not affect each other.

2. Application scenarios of deep copy

JSON.parse(JSON.stringify(object))

/ / wooden Yi Yang
let a = {
    name: "muyiy".book: {
        title: "You Don't Know JS".price: "45"}}let b = JSON.parse(JSON.stringify(a));
console.log(b);
/ / {
// name: "muyiy",
// book: {title: "You Don't Know JS", price: "45"}
// } 

a.name = "change";
a.book.price = "55";
console.log(a);
/ / {
// name: "change",
// book: {title: "You Don't Know JS", price: "55"}
// } 

console.log(b);
/ / {
// name: "muyiy",
// book: {title: "You Don't Know JS", price: "45"}
// } 
Copy the code

Changing a completely has no effect on B, and that’s the magic of deep copy.

Let’s see how deep copy of an array works.

/ / wooden Yi Yang
let a = [0."1"[2.3]].let b = JSON.parse(JSON.stringify( a.slice(1)));console.log(b);
/ / [" 1 ", [2, 3]]

a[1] = "99";
a[2] [0] = 4;
console.log(a);
// [0, "99", [4, 3]]

console.log(b);
/ / [" 1 ", [2, 3]]
Copy the code

After making a deep copy of an array, changing the original array does not affect the copied array.

However, there are several problems with this approach.

1. Undefined is ignored

2, will ignore symbol

3. Functions cannot be serialized

4. Cannot resolve objects referenced by loop

Error handling new Date()

Cannot handle regex

  • undefined,symbolAnd the delta function, I’m just going to ignore it.
/ / wooden Yi Yang
let obj = {
    name: 'muyiy'.a: undefined.b: Symbol('muyiy'),
    c: function() {}}console.log(obj);
/ / {
// name: "muyiy",
// a: undefined,
// b: Symbol(muyiy),
//  c: ƒ ()
// }

let b = JSON.parse(JSON.stringify(obj));
console.log(b);
// {name: "muyiy"}
Copy the code
  • In circular reference cases, an error is reported.
/ / wooden Yi Yang
let obj = {
    a: 1.b: {
        c: 2.d: 3
    }
}
obj.a = obj.b;
obj.b.c = obj.a;

let b = JSON.parse(JSON.stringify(obj));
// Uncaught TypeError: Converting circular structure to JSON
Copy the code
  • new DateIn this case, the conversion result is incorrect.
/ / wooden Yi Yang
new Date(a);// Mon Dec 24 2018 10:59:14 GMT+0800 (China Standard Time)

JSON.stringify(new Date());
/ / ", "the 2018-12-24 T02:59:25. 776 z" "

JSON.parse(JSON.stringify(new Date()));
/ / "the 2018-12-24 T02:59:41. 523 z"
Copy the code

The solution is simply a string or timestamp.

/ / wooden Yi Yang
let date = (new Date()).valueOf();
/ / 1545620645915

JSON.stringify(date);
/ / "1545620673267"

JSON.parse(JSON.stringify(date));
/ / 1545620658688
Copy the code
  • In the canonical case,
/ / wooden Yi Yang
let obj = {
    name: "muyiy".a: / / '123'
}
console.log(obj);
// {name: "muyiy", a: /'123'/}

let b = JSON.parse(JSON.stringify(obj));
console.log(b);
// {name: "muyiy", a: {}}

Copy the code

PS: Why do these problems exist? Take a look at JSON.

Extend () and lodash.clonedeep (), which are common in jquery.extend () and lodash.clonedeep ().

Four,

And whether the original data points to the same object The first layer of data is the basic data type The raw data contains child objects
The assignment is Change causes the original data to change with it Change causes the original data to change with it
Shallow copy no changeDon’tIt changes the original data along with it Change causes the original data to change with it
Deep copy no changeDon’tIt changes the original data along with it changeDon’tIt changes the original data along with it

reference

Js deep copy vs shallow copy

Java deep copy and shallow copy

The Object of MDN. Assign ()

Expansion syntax of MDN

The Array of MDN. Prototype. Slice ()

Advanced series catalog

  • The call stack
  • Scoped closures
  • 【 advanced 3 stage
  • The principle of deep and shallow copy
  • 【 典 型 例 句 1 】 I’m a Prototype
  • Higher-order functions
  • Event mechanism
  • [Advanced phase 8] Event Loop principle
  • The Promise Principle
  • The principle of Async/Await
  • Anti – shake/throttling principle
  • [Advanced 12] Modular details
  • 【 advanced 13 】ES6
  • An overview of computer networks
  • The principles of browser rendering
  • Webpack configuration
  • The Webpack Principle
  • [Advanced phase 18] Front-end monitoring
  • Cross domain and security
  • [Advanced 20 issues] Performance optimization
  • [Advanced 21] Principles of VirtualDom
  • Diff algorithm
  • MVVM bidirectional binding
  • The Vuex principle
  • Redux’s Principle
  • Routing principles
  • [Advanced 27] VueRouter source code parsing
  • ReactRouter source code parsing

communication

Advanced series of articles summary: github.com/yygmind/blo… , with high quality front-end data, feel good to point a star.

My name is Mu Yiyang, a senior front-end engineer of netease. I will focus on one front-end interview every week. Next, let me take you into the world of advanced front-end, on the way to progress, mutual encouragement!