When working with Javascript and using the extend function in the underscore.js library, I am curious about what happens in relation to memory. Consider this example:
var obj = {hello: [2]};
var obj2 = {hola: [4]};
_.extend(obj, obj2)
obj2.hola = 5;
console.log(obj) // The value of hola still remains as `[4]`
I am puzzled by the fact that even after manipulating obj2, hola's value remains unchanged when inspecting obj. I expected the value to update because of pass by reference...
In my mind, here is a visualization of the process:
The extend function copies the key
hola
into obj:obj = {hello: [2], hola: TBD}
My assumption is that hola now points to the value
[4]
, hence I believe obj would beobj = {hello: [2], hola: #0x93490234}
This is why I expected to see a value of 5 under obj. Can you help me understand where my visualization might be going wrong?
Furthermore, could you explain why the above scenario differs from this simpler example (which I grasp conceptually)?
var obj2 = {hola: [4]};
var obj = obj2;
obj2.hola = 5; // Upon console.logging obj, it will display hola equals 5