我在嘗試創建一個Dictionary對象時遇到了一個奇怪的錯誤。很基本的東西。但是,當我創建對象的2個實例,然後設置一個值時,它們出現在兩者上。我在這裏做錯了什麼?兩個實例包含相同的值
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());
原型上的對象在所有實例之間共享關於強制正確使用的所有實例 – 2012-03-17 00:46:36
[本文](http://gotochriswest.com/blog/2011/05/17/forcing-a-constructor-in-javascript/)如果你個人不是你的代碼的唯一消費者(或者你只是不信任你自己),那麼構造函數可能會對你感興趣。 – jbabey 2012-03-17 00:49:53