Guest User

Untitled

a guest
Feb 24th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>Looks like a quirk, but isn't it simply pass by reference?</title>
  7. </head>
  8. <body>
  9.  
  10. <script id="jsbin-javascript">
  11. var foo = {n: 1};
  12. var bar = foo;
  13. foo.x = foo = 2;
  14.  
  15. console.log(JSON.stringify(foo));
  16. console.log(JSON.stringify(bar));
  17.  
  18. console.log('RHS foo = {n: 2}; evaluates to {n: 2}, LHS foo.x refers to the old object, so the object is now {x: {n:2}, n: 1}');
  19. console.log('But then what is foo.x? Looks like it\'s undefined');
  20. console.log('How the hell is that possible? See, whenever we write fizz.buzz = ... we are passing by reference. when doing fizz = {...} that\'s creating a new object in the memory.');
  21. console.log('So here, we can treat the weird code like so: {n: 1}.x = (foo = {n:2})');
  22. console.log('As a rule, you can remember that by using a dot, you are referring to the object, and when not using a dot and simply doing myVar = that creates a new memory space, without affecting the reference to the old primitive/object myVar was pointing to.')
  23. </script>
  24.  
  25.  
  26.  
  27. <script id="jsbin-source-javascript" type="text/javascript">var foo = {n: 1};
  28. var bar = foo;
  29. foo.x = foo = 2;
  30.  
  31. console.log(JSON.stringify(foo));
  32. console.log(JSON.stringify(bar));
  33.  
  34. console.log('RHS foo = {n: 2}; evaluates to {n: 2}, LHS foo.x refers to the old object, so the object is now {x: {n:2}, n: 1}');
  35. console.log('But then what is foo.x? Looks like it\'s undefined');
  36. console.log('How the hell is that possible? See, whenever we write fizz.buzz = ... we are passing by reference. when doing fizz = {...} that\'s creating a new object in the memory.');
  37. console.log('So here, we can treat the weird code like so: {n: 1}.x = (foo = {n:2})');
  38. console.log('As a rule, you can remember that by using a dot, you are referring to the object, and when not using a dot and simply doing myVar = that creates a new memory space, without affecting the reference to the old primitive/object myVar was pointing to.')
  39.  
  40.  
  41.  
  42.  
  43.  
  44. </script></body>
  45. </html>
Add Comment
Please, Sign In to add comment