0

Here is the code:

 var a = {};
 var b = {name:"Spork"};

 function connect(o1,o2){
    o1 = o2;
 };

 connect(a,b);

 console.log(a);
 console.log(b);

It prints: {}{name:"Spork"}

It should be: {name:"Spork"}{name:"Spork"}

Please tell me why at the end a doesn't point at b. If objects are passed by reference in a function, I thought that my function tells a to point at the same memory space as b.

Aamir
  • 2,380
  • 3
  • 24
  • 54
Alex
  • 3
  • 1
  • In short, references themselves are passed by value. http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – uylmz Dec 19 '15 at 10:10

2 Answers2

0

Its all about visibility of your variables, see you are declaring var a = {}; var b = {name:"Spork"}; outside of connect method ok and then you are passing them to the connect method, o1 and o2 are local to connect method and whatever changes happens inside connect method will not be reflected outside of it, thatz why on printing them you are not empty value of a

Aamir
  • 2,380
  • 3
  • 24
  • 54
0

"Passing by reference" is just an abstraction; you are actually passing by value the reference to an object in memory. So o1 and o2 are distinct variables containing the same references that a and b contain.

In simpler terms, a and o1 are two different containers with the same contents. Same with b and o2.

Since o1 and o2 are independent of a an b, assigning one reference to the other does nothing outside of the function; all that does is overwrite the reference in o1, which means o1 and o2 will reference the same object..

What you want is to modify the objects that the references point to. In your case, you want to copy over all the properties from one object (namely, the object pointed to by o2) into another object (the object pointed to by o1).

Javascript offers a convenient way to do this using Object.assign():

function connect(o1, o2){
    Object.assign(o1, o2);
}

Here's a demo.

Purag
  • 16,941
  • 4
  • 54
  • 75