i am a bit obscure situation. mainly because i thought i already grasp closures. so basically what i want is to reset to default values a collection. so let say i have collectio
This has nothing to do with closures. Your issue can be seen simpler with this:
var internalarray = [{x},{y},{z}];
var arr = internalarray;
// "update" internalarray here
arr === internalarray // still true
internalarray = arr; // This statement has no effect
Just like in Java, every value in JavaScript is either a primitive or a reference (a pointer to an object). The value of arr
is a pointer to an object, the value of c
is a pointer to an object, the value of c.internalarray
is a pointer to an object, etc. Specifically in this case, c.internalarray
is a pointer to an array object. Assigning one pointer to another simply makes the second one point to the object pointed to by the first one. When you do arr = internalarray;
(or in your code, when you pass c.internalarray
in to a function as the parameter arr
), you have two pointers that point to the same object.
When you say "collection periodically get updated", you are never assigning (as in =
) to c.internalarray
itself. That's why arr === c.internalarray
remains true -- since you assigned one to the other initially, the only way they could be not equal is if you assigned to one of them later. Instead, I am guessing you are changing the elements of the array pointed by these two variables, using subscript operator like c.internalarray[foo] = bar;
or calling a method like c.internalarray.push(bar);
. Since you are changing the object pointed to, multiple pointers that point to it will be able to see the changes.