Analyze the difference between basic data types and reference data types in JS from simple to in-depth

Time:2021-7-30

one   Data classification of JS in a broad sense

JS is divided into two data types:

1. Basic data type: number, string, null, Bollean, undefined, symbol (ES6)

Whether it can be changed: no (when the basic data type is re assigned, it will point to a new memory address, and the old one will not be changed. A special article may be written later ✨)

Location of data storage: stack memory (heap and stack may also open a separate article ✨)

2. Reference data types: array, object, function, etc. (some people say that all these in JS are derived from object encapsulation. An object can be understood as a reference pointer to memory stored in stack memory. The disappearance of the pointer may trigger JS garbage collection mechanism ✨)

Whether it can be changed: Yes

Data storage location: heap memory

two   Basic data type

const a = 10

let b = 10

let a = 20

Analyze the difference between basic data types and reference data types in JS from simple to in-depth

three   Reference data types and shallow copies

const obj1={a:123}

const obj2 = obj1 

const dataA = obj1.a

console.log(JSON.stringify(obj2))

Obj2. B = "this is a B of obj2"

obj2.a=567

obj2.c={name:"name"}

console.log(JSON.stringify(obj1))

console.log(JSON.stringify(obj2))

console.log(dataA)

Operation results:

Analyze the difference between basic data types and reference data types in JS from simple to in-depth

Analyze the difference between basic data types and reference data types in JS from simple to in-depth

four   Deep copy

When we do not want the copied object to inherit the memory address pointed to by the original object, we need to make a deep copy. Here, we use recursion to re assign each attribute in the object

const Copy=(obj)=>{
 if (!obj) {
 return obj
 }
 if (typeof obj!=="object") {
 return obj
 }
 if (obj.constructor===Date) {
 return new Date(obj)
 }
 const newObj=new obj.constructor() _// Maintain inheritance chain_
 for (const key in obj) {
 if (obj.hasOwnProperty(key)) {
 const element = obj[key];
 newObj[key] = typeof element === "object" ? Copy(element) : element
 }
 }
 return newObj
}
const obj3 = Copy(obj1)
obj3.b="obj3"
console.log(JSON.stringify(obj3))
const array = Copy(["obj1", "obj2", "obj3"])
console.log(array)

Then run the above code to get the result

Analyze the difference between basic data types and reference data types in JS from simple to in-depth

5. Summary

1. The basic data type and reference data type store data in stack memory and heap memory respectively

2. Referring to the structure of data type will lead to inheritance

3. Deep copy is to reassign the data in the heap memory