Why does this work? Object references in Javascript

后端 未结 3 1201
半阙折子戏
半阙折子戏 2020-12-20 19:27

I\'ve finally been curious enough to find out why javascript does its voodoo magic to learn why not all object references are created equal.

Given the example:

相关标签:
3条回答
  • 2020-12-20 20:08

    The value of a that is assigned to b is a Number. The value assigned from c to d is a reference to an Object.

    var a, b, c, d;
    a = 100; // a has value 100, a number
    b = a; // b has value 100, a number
    
    c = {}; // c has value p, a reference to some object P
    d = c; // d has value p, a reference to P
    
    b = 10; // b has value 10, a number
    d.e = 'f'; // P.e has value 'f', a string
    
    0 讨论(0)
  • 2020-12-20 20:17

    All variables in JavaScript are not objects. There are native types as well.

    c and d are not linked to one another. They are pointing to the same object reference. If you were to reassign d to something else, it will not affect c.

    var c = {};
    var d = c;
    d = { foo: "bar" };
    
    c === d // false
    

    However, if you were to modify the object being referenced by c or d, it will modify the same object since c and d are both referring to the same object as in your example.

    0 讨论(0)
  • 2020-12-20 20:24

    It looks to me that the difference is with b, you're reassigning the variable to a new object/value, while with d, you're modifying the existing object.

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