Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <script>
- let obj1, obj2, obj3, obj4;
- // Shallow Copy and Deep Copy
- obj1 = {
- x: 2,
- y: 3
- }
- // Shallow Copy: The values of obj1 changes
- obj2 = obj1;
- obj2.x = 5;
- console.log(obj1, obj2); // {x: 5, y: 3} {x: 5, y: 3}
- // Deep Copy: The values of obj1 remains unchanged
- // Method 1: Use Object.assign()
- obj3 = Object.assign({}, obj1);
- obj3.x = 56;
- console.log(obj1, obj3); // {x: 5, y: 3} {x: 56, y: 3}
- // Method 2: Use JSON.parse(JSON.stringify())
- obj4 = JSON.parse(JSON.stringify(obj1));
- obj4.x = 10;
- console.log(obj1, obj4); // {x: 5, y: 3} {x: 10, y: 3}
- </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement