Rumah >hujung hadapan web >tutorial js >Fahami Rujukan dan Penyalinan Objek JavaScript - Penjelasan Ringkas
Apabila bekerja dengan objek dalam JavaScript, memahami perbezaan antara rujukan objek dan penyalinan objek adalah penting. Berikut ialah gambaran keseluruhan terperinci:
let obj1 = { name: "Alice" }; let obj2 = obj1; // obj2 now references the same object as obj1 obj2.name = "Bob"; console.log(obj1.name); // Output: "Bob"
let a = { key: "value" }; let b = { key: "value" }; console.log(a === b); // Output: false (different references) let c = a; console.log(a === c); // Output: true (same reference)
Terdapat dua jenis penyalinan objek utama: salinan cetek dan salinan dalam.
Teknik untuk Salinan Cetek:
Object.assign():
let original = { name: "Alice", details: { age: 25 } }; let copy = Object.assign({}, original); copy.details.age = 30; console.log(original.details.age); // Output: 30 (shared reference)
Pengendali sebaran (...):
let original = { name: "Alice", details: { age: 25 } }; let copy = { ...original }; copy.details.age = 30; console.log(original.details.age); // Output: 30 (shared reference)
Kedua-dua kaedah mencipta salinan cetek, bermakna objek bersarang masih dipautkan.
Teknik untuk Salinan Dalam:
JSON.parse() dan JSON.stringify():
let original = { name: "Alice", details: { age: 25 } }; let copy = JSON.parse(JSON.stringify(original)); copy.details.age = 30; console.log(original.details.age); // Output: 25
StructuredClone() (JavaScript Moden):
let original = { name: "Alice", details: { age: 25 } }; let copy = structuredClone(original); copy.details.age = 30; console.log(original.details.age); // Output: 25
Perpustakaan Tersuai:
let obj1 = { name: "Alice" }; let obj2 = obj1; // obj2 now references the same object as obj1 obj2.name = "Bob"; console.log(obj1.name); // Output: "Bob"
Action | Result |
---|---|
Assignment (=) | Creates a reference. Changes to one variable affect the other. |
Shallow Copy | Creates a new object but retains references for nested objects. |
Deep Copy | Creates a completely independent object, including nested structures. |
Hasil
Atas ialah kandungan terperinci Fahami Rujukan dan Penyalinan Objek JavaScript - Penjelasan Ringkas. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!