I'm confused by this closure behavior. I've read several SO articles (including this one) and MDN's documentation on closures, but haven't seen the explanation for this behavior.
In the code sample below I'm creating a closure containing a variablecache
, a function preload
that modifies it, and a function report
that logs its value. It also attaches references to those to an object that is passed in.
'use strict';
var o = {};
(function(obj) {
var cache = {'initialized': false};
function preload(assets, done) {
console.log('Preloading. Value of cache is', cache);
cache = {};
for (var i = 0; i < assets.length; i++) {
cache[assets[i]] = assets[i];
}
}
function report() {
console.log('Cache from inside is ', cache);
}
function get_cache() {
return cache;
}
obj.cache = cache;
obj.preload = preload;
obj.report = report;
} )(o);
// {initialized: false}, as expected
o.report();
// {initialized: false}, as expected
console.log('Cache from outside is ', o.cache);
// I expect this to change cache to {1:1, 2:2, 3:3}
o.preload([1, 2, 3]);
// {1:1, 2:2, 3:3}, as expected
o.report();
// {initialized: false}, NOT as expected. Why?
console.log('Cache from outside is ', o.cache);
My expectation is based on my understanding that when the closure attaches cache
to the provided obj
, it is assigning a reference to the variable within the closure. But the behavior I'm seeing suggests that obj.cache
is getting a copy of the closure's cache
.
At which point is a copy of cache
created and why?