title: Preventing accidental alteration of a javascript prototype
body: <p>I have run into some trouble with finding a way to prevent accidental alterations of an object's prototype. The example below should help clarify my issue:</p>
  
  <pre><code>var Enemy, enemy1, enemy2;
  
  Enemy = (function() {
    function Enemy() {}
  
    Enemy.prototype.speed = 10;
  
    Enemy.prototype.stats = {
      strength: 15
      dexterity: 12
    };
  
    return Enemy;
  
  })();
  
  enemy1 = new Enemy();
  enemy2 = new Enemy();
  
  enemy1.speed = 20;
  enemy1.stats.strength = 25;
  
  console.log("enemy1 speed: " + enemy1.speed);
  console.log("enemy2 speed: " + enemy2.speed);
  console.log("enemy1 str: " + enemy1.stats.strength);
  console.log("enemy2 str: " + enemy2.stats.strength);
  </code></pre>
  
  <p>Result:</p>
  
  <pre><code>console: enemy1 speed: 20
  console: enemy2 speed: 10
  console: enemy1 str: 25
  console: enemy2 str: 25
  </code></pre>
  
  <p>As you can see, editing a primitive property on enemy1 (e.g. <code>speed</code>) does not affect enemy2. But when a property within an object property is changed on enemy1 (e.g. <code>stats.strength</code>), this seems to actually be altering the prototype instead of the instance. </p>
  
  <p>I believe this is because neither enemy1 nor enemy2 have a local property called <code>stats</code>, so <code>enemy1.stats</code> resolves to the prototype value, meaning that its value for <code>strength</code> is altered.</p>
  
  <p>I have come up with a way to solve this, by changing Enemy's constructor to:</p>
  
  <pre><code>function Enemy() {
      //using jQuery to deep copy the stats property in the prototype
      this.stats = $.extend(this, Enemy.prototype.stats); 
  }
  </code></pre>
  
  <p>This initializes a local property of stats, which means a reference to <code>enemy1.stats</code> no longer references the prototype.</p>
  
  <p>But I'm not entirely happy with this approach as I need to remember to do this for each object property, when I add more. Not only that, but I've also now got fatter Enemy objects as they each need to store a copy of the stats object.</p>
  
  <p>Is there a better approach I can use here?</p>
  
  <p>Thanks!</p>