Home >Web Front-end >JS Tutorial >Understand JavaScript Object References and Copying - Brief Explanation
When working with objects in JavaScript, understanding the difference between object references and object copying is crucial. Here’s a detailed overview:
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)
There are two main types of object copying: shallow copy and deep copy.
Techniques for Shallow Copy:
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)
Spread operator (...):
let original = { name: "Alice", details: { age: 25 } }; let copy = { ...original }; copy.details.age = 30; console.log(original.details.age); // Output: 30 (shared reference)
Both methods create a shallow copy, meaning nested objects are still linked.
Techniques for Deep Copy:
JSON.parse() and 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() (Modern JavaScript):
let original = { name: "Alice", details: { age: 25 } }; let copy = structuredClone(original); copy.details.age = 30; console.log(original.details.age); // Output: 25
Custom Libraries:
let obj1 = { name: "Alice" }; let obj2 = obj1; // obj2 now references the same object as obj1 obj2.name = "Bob"; console.log(obj1.name); // Output: "Bob"
|
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. |
The above is the detailed content of Understand JavaScript Object References and Copying - Brief Explanation. For more information, please follow other related articles on the PHP Chinese website!