why the program's result is undefined?

后端 未结 2 1786
迷失自我
迷失自我 2020-12-15 13:16
 var foo = {};
 foo.c = foo = {};
 console.log(foo.c);

why the result is undefined? i thought it is supposed to be \'[object Object]\'

相关标签:
2条回答
  • 2020-12-15 13:46

    Strange things are happening here in the assignments:

    foo.c = (foo = {})
    

    The reference to foo.c is resolved first and points to the old foo object, before the inner expression is evaluated where foo is re-assigned with the {} emtpy object literal. So your code is equivalent to

    var foo1 = {};
    var foo2 = {};
    foo1.c = foo2;
    console.log(foo2.c) // obviously undefined now
    

    You can also try

    var foo = {}, old = foo;
    foo.c = foo = {};
    console.log(old, foo, old.c===foo); // {c:{}}, {}, true
    
    0 讨论(0)
  • 2020-12-15 13:56

    JavaScript engine splits such assignment:

    a = b = c = 1;
    

    As follow:

    a = 1;
    b = 1;
    c = 1;
    

    And not as:

    c = 1;
    b = c;
    a = b;
    

    There is a slightly but important difference – mostly, it involves getters, please check Multiple variable assignments in one row for further details – and that's mostly why your code doesn't behave like expected, because the initial expectations are based on false assumptions.

    0 讨论(0)
提交回复
热议问题