Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width">
- <title>Looks like a quirk, but isn't it simply pass by reference?</title>
- </head>
- <body>
- <script id="jsbin-javascript">
- var foo = {n: 1};
- var bar = foo;
- foo.x = foo = 2;
- console.log(JSON.stringify(foo));
- console.log(JSON.stringify(bar));
- 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}');
- console.log('But then what is foo.x? Looks like it\'s undefined');
- 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.');
- console.log('So here, we can treat the weird code like so: {n: 1}.x = (foo = {n:2})');
- 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.')
- </script>
- <script id="jsbin-source-javascript" type="text/javascript">var foo = {n: 1};
- var bar = foo;
- foo.x = foo = 2;
- console.log(JSON.stringify(foo));
- console.log(JSON.stringify(bar));
- 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}');
- console.log('But then what is foo.x? Looks like it\'s undefined');
- 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.');
- console.log('So here, we can treat the weird code like so: {n: 1}.x = (foo = {n:2})');
- 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.')
- </script></body>
- </html>
Add Comment
Please, Sign In to add comment