简体   繁体   中英

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

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM