What is passed by reference / value in JavaScript?

This question already has an answer here:

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

  • Your testing code is just wrong. In the occations you see you are "passing by reference", that doesn't mean you are "passing by reference", it means you are changing the contents of the object/array, not the object reference itself.

    Where you see you are "passing by value", it's because the value you set hasn't changed.

    When you assign str , or obj2 , or arr2 (the ones your code say are "by value"), you are setting a new reference on the inner scoped parameter variable. You are not changing the outer one. So when you print it (outside the test function) it just maintains the value it was assigned.

    Likewise, the ones you see are passed "by reference", you are just changing their properties, the "content" of the variable. If you do:

    obj1.val = "Obj1 was passed by reference!";
    

    Then you are setting "val", not "obj1". That's why you see it changes "outside". Or when you do:

    arr1[0] = 'r';
    arr1[1] = 'e';
    arr1[2] = 'f';
    

    You are setting "element 0 of arr1", "element 1 of arr1", etc., not "arr1".

    So your code doesn't prove what you are thinking it proves.

    You are mutating the objects in some cases, and assigning different objects in others, and that's the actual difference you are seeing, not the "passing by reference or value".

    By the way, Javascript can't "pass by reference" in the way you want it to. You can't just set a scoped argument variable value and pretend it changes outside that scope. Other languages allow you to do this, but not Javascript. You pass a reference (a pointer) to the object in the contents of the argument, but the argument itself is not related to the "variable you pass in", in any way (other than they originally point to the same object)

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

    上一篇: 数组,字符串和.join()

    下一篇: JavaScript中引用/值传递了什么?