我可以用这个简单的代码片段最好的解释这个问题:为什么我在使用相同缓存对象的`jQuery.extend`两个对象时有共享缓存?
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'));
现在为什么它会返回123的时候我们只访问child1的writeCache()?
这看起来像是关于jQuery的扩展方法,而不是Javascript的继承。 – thomasrutter