"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.