Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does'nt my js code reflect the right runtime value?

Tags:

javascript

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...

like image 940
d11 Avatar asked Mar 20 '26 22:03

d11


2 Answers

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.

like image 66
Halcyon Avatar answered Mar 23 '26 10:03

Halcyon


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 }
like image 26
p.s.w.g Avatar answered Mar 23 '26 12:03

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!