两个实例包含相同的值

Mat*_*hew 1 javascript inheritance

在尝试创建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());
Run Code Online (Sandbox Code Playgroud)

Bru*_*lva 5

您在items原型中定义了这意味着它将由所有实例共享.您需要在"构造函数"函数中设置它并将其从原型中删除.

function Dict() { this.items = []; }
Run Code Online (Sandbox Code Playgroud)

我已经为您创建了一个JS小提琴,其完整的源代码位于http://jsfiddle.net/brunomsilva/zaSY2/.