I can explain the problem best with this simple code snippet:
var child1 = {name: 'child1'};
var child2 = {name: 'child2'};
var parent = {
_cache: [], // storage var
writeCache: function(key, val)
{
console.log('writing cache::'+this.name);
this._cache[key] = val;
},
readCache: function(key)
{
if(this._cache[key] == undefined)
{
return false;
}
return this._cache[key];
},
};
jQuery.extend(child1, parent);
jQuery.extend(child2, parent);
child1.writeCache('myKey', 123);
console.log(child1.readCache('myKey')); // returns 123 as expected
console.log(child2.readCache('myKey')); // returns 123 unexpectedly (for me at least)
See this last line:
console.log(child2.readCache('myKey'));
Now why does it return 123 when we’ve accessed only child1’s writeCache()?
jQuery’s extend method makes a copy of everything in the second object and puts it in the first object.
That includes copying the reference to the array you assign to
parent._cache. As a result, whenever you read or write from any objects cache, you access the same data store.To avoid this, make a deep copy.
As an aside, since you are dealing with named keys, use an Object, not an Array.