SHARE
TWEET

Untitled

a guest May 19th, 2019 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script>
  2.   let obj1, obj2, obj3, obj4;
  3.   // Shallow Copy and Deep Copy
  4.   obj1 = {
  5.       x: 2,
  6.       y: 3
  7.   }  
  8.  
  9.   // Shallow Copy: The values of obj1 changes
  10.   obj2 = obj1;
  11.   obj2.x = 5;
  12.   console.log(obj1, obj2); // {x: 5, y: 3} {x: 5, y: 3}
  13.  
  14.   // Deep Copy: The values of obj1 remains unchanged
  15.   // Method 1: Use Object.assign()
  16.   obj3 = Object.assign({}, obj1);
  17.   obj3.x = 56;
  18.   console.log(obj1, obj3); // {x: 5, y: 3} {x: 56, y: 3}
  19.  
  20.   // Method 2: Use JSON.parse(JSON.stringify())
  21.   obj4 = JSON.parse(JSON.stringify(obj1));
  22.   obj4.x = 10;
  23.   console.log(obj1, obj4); // {x: 5, y: 3} {x: 10, y: 3}
  24. </script>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top