I’m running into a bizarre bug while trying to create a Dictionary object. Pretty basic stuff. However when I create 2 instances of the object, and then set some values on one, they appear on both. What am I doing wrong here?
function Dict() { }
Dict.prototype = {
items: { },
prop: function(key) {
return ':' + key;
},
get: function(key, def) {
var p = this.prop(key),
k = this.items;
return k.hasOwnProperty(p) ? k[p] : def;
},
set: function(key, value) {
var p = this.prop(key);
this.items[p] = value;
return value;
},
count: function() {
return Object.keys(this.items).length;
},
has: function(key) {
var p = this.prop(key);
return this.items.hasOwnProperty(p);
},
del: function(key) {
var p = this.prop(key),
k = this.items;
if(k.hasOwnProperty(p))
delete k[p];
},
keys: function() {
return Object.keys(this.items).map(function(key) {
return key.substring(1);
});
}
};
var a = new Dict();
var b = new Dict();
a.set('foo', 'bar');
console.log(a.keys());
console.log(b.keys());
The
itemsproperty is set on theprototype. The prototype is not cloned when creating an object, soitemsis the same on the twoDicts. Setitemsin the constructor so each object has its own:Prototypes work because when you try to access an object’s property, it first checks the object’s own properties to see if it contains it. If so, that’s the value. If it’s not found there, it checks the prototype. If it’s not there, it continues traversing the chain of prototypes until it finds the property. If it’s still not found, it results in
undefined. (for more detail, see the specification)