Variable References Changing

This question already has an answer here:

  • Javascript by reference vs. by value [duplicate] 4 answers

  • Primitive data types (number, string and boolean) do not change if you change a reference of it, whereas composite data types do change.

    http://msdn.microsoft.com/en-us/library/ie/7wkd9z69(v=vs.94).aspx


    In javascript Arrays & Objects are passed by reference, so changing them one place affects others.

    And primitives like number , string are passed by value, so changing them at one place doesn't affect on others.

    Primitives

    var a,b;
    a=10;
    b=a;
    

    So b & a has something like bellow structure

    a ---1000----> [10] a is pointing to some location(lets 1000) which have value 10
    b ---1004----> [10] b is pointing to some location(lets 1004) which have value 10
    

    Lets we increment a by 1 now the value will be changed at the place 1000 .

    a ---1000----> [11]
    b ---1004----> [10]
    

    And in Arrays and Objects

    obj1 = {}; // obj1 has a reference
    

    obj1 has an structure like bellow

    ------->1000--------->[{}]
    obj1 -------1004----->[1000] //this '1000' is a reference which has a `{}` at it's place 
    

    This line

    obj2 = obj1;
    

    after this line obj2 & obj share same reference ------->1000--------->[{}] obj1 -------1004----->[1000] obj2 -------1008----->[1000]

    obj1.ab = 5; 
    

    this line is adding a field called ab to the reference of obj1

    ------->1000--------->[{ab:5}]
    obj1 -------1004----->[1000]
    obj2 -------1008----->[1000]
    

    And because obj1 & obj2 have same reference, you are getting the field ab for both.

    obj1      // Object {ab: 5}
    obj2      // Object {ab: 5}
    

    Note:- Any improvement in answer is appreciated.


    arr1 contain a reference for the empty list. Then arr3 receives a reference for the same list, and arr2 a reference for the same list. So when you make arr1.ab = 5, you added a item in that list named 'ab' and gave the value 5. But since arr2 and arr3 point to the same list, you will get the same value.

    链接地址: http://www.djcxy.com/p/20984.html

    上一篇: 为什么=不能改变数组,但推可以?

    下一篇: 变量引用更改