Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Khác biệt Deep Copy và Shallow Copy trong JavaScript

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ápLoạiHỗ trợLưu ý
Object.assign / {...obj}Shallow1 levelNhanh, ES6
JSON parse/stringifyDeepJSON-safeMất function, Date, RegExp, circular
structuredClone()DeepModern typesES2022, hỗ trợ cyclic, Date, Map, Set
Lodash cloneDeepDeepMọi thứCần dependency