When I run this code (under a <script> code)
window.msg = { a: 0}
var b = window.msg;
function g()
{
console.log(b)
}
msg = { a: 1};
g()
in the console - I get {a: 0} .
why is that ? I thought that msg = { a: 1}; will update the reference...
If you change your code to:
window.msg = { a: 0}
var b = window.msg;
function g()
{
console.log(b)
}
msg.a = 1; // this line is changed
g()
You will get {a:1}.
You're reassigning msg so b just points to the old value of msg.
b does not reference window.msg but the {a:0} object.
You're are creating the object { a: 0 }, and assigning a reference to that object to msg and b. Later, you're creating a new object { a: 1 }, and assigning a reference to that object to msg, but b is still referencing the original object:
window.msg = { a: 0} // msg --> { a: 0 }, b --> undefined
var b = window.msg; // msg --> { a: 0 }, b --> { a: 0 }
msg = { a: 1}; // msg --> { a: 1 }, b --> { a: 0 }
g() // prints b --> { a: 0 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With