Shallow Copy และ Deep Copy เป็น Language Agnostic Shallow Copies Duplicate น้อยที่สุด Shallow Copy ของ Collection คือ Copy ของ Structure ของ Collection ไม่ใช่ Elements ด้วย Shallow Copy สอง Collections จะ Share Individual Elements เดียวกัน
ตัวอย่าง
let innerObj = { a: 'b', c: 'd' } let obj = { x: "test", y: innerObj } // Create a shallow copy. let copyObj = Object.assign({}, obj); // Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected. innerObj.a = "test" console.log(obj) console.log(copyObj)
ผลลัพธ์
{ x: 'test', y: { a: 'test', c: 'd' } } { x: 'test', y: { a: 'test', c: 'd' } }
สังเกตว่า Shallow Copies ไม่ Clone แบบ Recursive เพียง Top Level เท่านั้น
Deep Copies Duplicate ทุกอย่าง Deep Copy ของ Collection คือ สอง Collections พร้อม Elements ทั้งหมดใน Original Collection ถูก Clone
ตัวอย่าง
let innerObj = { a: 'b', c: 'd' } let obj = { x: "test", y: innerObj } // Create a deep copy. let copyObj = JSON.parse(JSON.stringify(obj)) // Both copyObj and obj's prop y now refers to the same innerObj. Any changes to this will be reflected. innerObj.a = "test" console.log(obj) console.log(copyObj)
ผลลัพธ์
{ x: 'test', y: { a: 'test', c: 'd' } } { x: 'test', y: { a: 'b', c: 'd' } }