Shallow copy: Copy ít nhất có thể. Copy cấu trúc collection, không copy element. Hai collection share cùng element object.
Ví dụ Shallow Copy
let innerObj = { a: 'b', c: 'd' };
let obj = { x: "test", y: innerObj };
let copyObj = Object.assign({}, obj); // Shallow copy
innerObj.a = "test";
console.log(obj); // { x: 'test', y: { a: 'test', c: 'd' } }
console.log(copyObj); // { x: 'test', y: { a: 'test', c: 'd' } }
Kết quả
{ x: 'test', y: { a: 'test', c: 'd' } } { x: 'test', y: { a: 'test', c: 'd' } }
Thay đổi innerObj ảnh hưởng cả obj và copyObj vì share reference.
Deep Copy
Nhân bản mọi thứ. Hai collection độc lập hoàn toàn.
let innerObj = { a: 'b', c: 'd' };
let obj = { x: "test", y: innerObj };
let copyObj = JSON.parse(JSON.stringify(obj)); // Deep copy
innerObj.a = "test";
console.log(obj); // { x: 'test', y: { a: 'test', c: 'd' } }
console.log(copyObj); // { x: 'test', y: { a: 'b', c: 'd' } }
Kết quả
{ x: 'test', y: { a: 'test', c: 'd' } } { x: 'test', y: { a: 'b', c: 'd' } }
So sánh phương pháp:
| Phương pháp | Loại | Hỗ trợ | Lưu ý |
|---|---|---|---|
| Object.assign / {...obj} | Shallow | 1 level | Nhanh, ES6 |
| JSON parse/stringify | Deep | JSON-safe | Mất function, Date, RegExp, circular |
| structuredClone() | Deep | Modern types | ES2022, hỗ trợ cyclic, Date, Map, Set |
| Lodash cloneDeep | Deep | Mọi thứ | Cần dependency |