วิธีที่ง่ายที่สุดในการโคลนอ็อบเจ็กต์ยกเว้นคีย์เดียวคือการโคลนอ็อบเจ็กต์ทั้งหมด แล้วลบคุณสมบัติที่ไม่จำเป็นออก อย่างไรก็ตาม การโคลนนิ่งสามารถมีได้ 2 ประเภท -
- โคลนลึก
- โคลนตื้น
สำเนาตื้น ทำสำเนาให้น้อยที่สุด สำเนาตื้นของการรวบรวมคือสำเนาของโครงสร้างการรวบรวม ไม่ใช่องค์ประกอบ ด้วยการคัดลอกแบบตื้น ตอนนี้คอลเลกชั่นสองคอลเลกชั่นจะแชร์องค์ประกอบแต่ละอย่างร่วมกัน
ตัวอย่าง
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)
This will give the output:
{ x: 'test', y: { a: 'test', c: 'd' } }
{ x: 'test', y: { a: 'test', c: 'd' } } โปรดทราบว่าสำเนาแบบตื้นจะไม่สร้างสำเนาแบบเรียกซ้ำ ทำได้แค่ระดับบนสุด
สำเนาลึกทำซ้ำทุกอย่าง สำเนาลึกของคอลเล็กชันคือคอลเลกชั่นสองคอลเลกชั่น โดยที่องค์ประกอบทั้งหมดในคอลเล็กชันดั้งเดิมถูกโคลน
ตัวอย่าง
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)
This will give the output:
{ x: 'test', y: { a: 'test', c: 'd' } }
{ x: 'test', y: { a: 'b', c: 'd' } } เมื่อคุณได้สำเนาโดยใช้วิธีใดวิธีหนึ่งเหล่านี้ คุณสามารถลบพร็อพเพอร์ตี้ที่คุณไม่ต้องการได้โดยใช้คำสำคัญลบ ตัวอย่างเช่น
ตัวอย่าง
let original = { x: 'test', y: { a: 'test', c: 'd' } }
let copy = JSON.parse(JSON.stringify(original))
delete copy['x']
console.log(copy)
console.log(original)
This will give the output:
{ y: { a: 'test', c: 'd' } }
{ x: 'test', y: { a: 'test', c: 'd' } }