title: Validity of JavaScript Type Parameters?
body: <p>Recently I stumbled across that JavaScript allows you to pass an object or array as the key to an object parameter. ex:</p>
  
  <pre><code>var myType = { 'Name':'MyType' };
  var myObject = {};
  myObject[myType] = 1;
  </code></pre>
  
  <p>will make <code>myObject[myType];</code> return <code>1</code>
  From looking further into this, it seems like internally the object's <code>.toString()</code> method is being called and passed as the actual key. In the above example this actually breaks apart as that means what is really happening is <code>myObject['[object Object]']</code> is being set, meaning that any standard object passed in would access the same key.</p>
  
  <p>However, I decided to expand upon this by creating custom objects which would cause their <code>.toString()</code> method to instead return their constructor. This would mean that it would return a unique key for each object type. Based on this, I created the following example of using this technique to create relatively clean implementation of a type parameter:</p>
  
  <pre><code>function Cat() {}
  function Dog() {}
  
  function AnimalPack() {
      this.speech = "";
      this.size = 0;
  }
  
  AnimalPack[Cat] = function() {
      var pack = new AnimalPack();
      pack.speech = "mew";
      pack.size = 2;
      return pack;
  }
  
  AnimalPack[Dog] = function() {
      var pack = new AnimalPack();
      pack.speech = "bark";
      pack.size = 4;
      return pack;
  }
  
  AnimalPack.prototype.Speak = function() {
      var speak = [];
      for(var i=0; i&lt;this.size; i++) {
          speak.push(this.speech);
      }
      return speak.join(" ");
  }
  
  var catparty = new AnimalPack[Cat]();
  var dogparty = new AnimalPack[Dog]();
  </code></pre>
  
  <p>In this example <code>catparty.Speak()</code> will return <code>'mew mew'</code> and <code>dogparty.Speak()</code> will return <code>'bark bark bark bark'</code>.</p>
  
  <p>This could be used with native JavaScript types as well (String, Number, etc).</p>
  
  <p>This seems to work standard across all 5 major browsers (chrome, firefox, ie, safari, opera).</p>
  
  <p>I was wondering if there is some glaring flaw that I am not seeing in this technique, or if this is perhaps a valid way of implementing a type parameter?</p>
  
  <p>Thanks!</p>