我可以用这个简单的代码片段最好地解释这个问题:
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)
请参阅最后一行:
console.log(child2.readCache('myKey'));
现在,当我们只访问了 child1 的 writeCache() 时,为什么它会返回 123?
最佳答案
jQuery 的扩展方法复制第二个对象中的所有内容并将其放入第一个对象中。
这包括将引用复制到您分配给parent._cache
的数组。因此,每当您从任何对象缓存中读取或写入时,您都会访问相同的数据存储。
为避免这种情况,请进行深层复制。
jQuery.extend(true, child1, parent);
jQuery.extend(true, child2, parent);
顺便说一句,由于您正在处理命名键,因此请使用对象,而不是数组。
_cache: {}, // storage var
关于javascript - 当我 `jQuery.extend` 两个具有相同缓存对象的对象时,为什么我有共享缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7702232/