I have been doing some practice example with closures, and I wanted to dive into exactly what is happening in the following situation:
function createClosure(v, obj){
var numb = v;
var object = obj;
return function(){console.log("v = " + numb + "\nobj = " + object.value)}
}
var v = 2;
var obj = {value: 4};
var function1 = createClosure(v, obj);
Situation 1:
When function1();
is run, I get the following result in the console:
v = 2
obj = 4
So far so good. BUT now I tried to modify the variables outside of the closure, and then run function1
again:
Situation 2:
v = 6;
obj.value = 11;
function1();
and I got an interesting result:
v = 2
obj = 11
So when modifying v, that doesn't affect the value of numb
inside the closure, but when modifying obj.value
it does affect the value of object.value.
QUESTION: Why is this the case? Why the "double" standard so to speak. I initially would have thought that numb
would have obtained a copy of v
, as well as object
obtaining a copy of obj
, and hence not being linked with each other, but from the results, that seems not to be the case.
I might guess that it has to do with the way pointers work in JavaScript and it varying for how they interact with variables / objects in closure situations, but that is a guess.