Shallow Clone VS Deep Clone
Shallow Clone
It is copying the reference pointer of the object which means the new object is also pointing towards the same memory reference of the old object.Deep Clone
The object will produce a copy of itself, a new memory is allocated for the object and its contents.
Shallow Clone
Traversing object properties
1 | function shallowClone(source) { |
1 | let a1 = {b: {c: {}}; |
Object.assign()
1 | let obj1 = { a: 10, b: 20, c: 30 }; |
1 | let obj = { a: {a: "hello", b: 21} }; |
Deep Clone
JSON.parse
1 | const oldObj = { |
This is easy, but it does not suit some situations.
- Can not clone function or Array object
- Lose the constructor of Object
- Throw error when Objects have circular references
1 | // constructor |
Recursion
Check the object type.
1 | function isType(obj, type) { |
1 | function deepClone(source) { |
1 | // constructor |
But there is still a question: stack overflow.
Loop
We can use loop instead of recursion
1 | function cloneLoop(source) { |
Reference
https://juejin.im/post/5bc1ae9be51d450e8b140b0c
https://juejin.im/post/5abb55ee6fb9a028e33b7e0a
1 |