มี 2 วิธี copy objects ในทุกภาษา: deep copy และ shallow copy
Shallow copy และ deep copy เป็น language agnostic Shallow copies duplicate น้อยที่สุด Shallow copy ของ collection คือ copy ของ collection structure ไใช่ 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 recursively แค่ top level
Deep copies duplicate ทุกอย่าง Deep copy ของ collection คือสอง collections ที่ elements ทั้งหมดใน original ถูก 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' } }