title: Javascript prototypes and instance creation
body: <p>I apologize because this topic comes up a lot, but I have not been able to have this adequately explained in anything I've read today.</p>
  
  <p>I am trying to make a simple collection class (and learn about javascript prototyping at the same time) designed to store objects with a "name" property and lets its members be accessed by index or value. So far I've got this:</p>
  
  <pre><code>function Collection() {}
  Collection.prototype.constructor = Collection;
  Collection.prototype._innerList = [];
  Collection.prototype._xref = {};
  Collection.prototype.count = function () { return this._innerList.length; };
  Collection.prototype.add = function (obj) {
      this._xref[obj.name] = this._innerList.push(obj) - 1;
  }
  Collection.prototype.get = function (id) {
      if (typeof id == "string") {
          return this._innerList[this._xref[id]];
      } else {
          return this._innerList[id];
      }
  };
  </code></pre>
  
  <p><a href="http://jsfiddle.net/YrVFZ/" rel="noreferrer">http://jsfiddle.net/YrVFZ/</a></p>
  
  <p>The problem: </p>
  
  <pre><code>var foo = new Collection();
  foo.add({name: "someitem", value:"hello world"});   // foo.count()== 1
  
  var bar= new Collection();
  bar.add({name: "someotheritem", value:"hello world"}); // bar.count()== 2
  </code></pre>
  
  <p>Hmm...</p>
  
  <p>Basically, the new instance <code>bar</code> is created with all the properties having the current values of the data in <code>foo</code>. I know I can fix this by putting _xref, etc. inside the constructor, but I'm trying to understand how prototyping works. If I create a new instance, and make changes to the data in that instance, why would those values carry over when I create another new instance? </p>
  
  <p>If I make further changes to a property from the prototype of <code>foo</code> or <code>bar</code> they are independent, so it doesn't seem as if I'm somehow referencing the same instance of anything. So what is causing <code>bar</code> to be instantiated with the current values from <code>foo</code>?</p>