Private variables in inherited prototypes
<p>I think I have misunderstood how Javascript prototypal inheritance works. Specifically, the prototypes internal variables seem to be shared between multiple different sub-objects. It is easiest to illustrate with code:</p>

<pre><code>var A = function()
{
  var internal = 0;
  this.Increment = function()
  {
    return ++internal;
  };
};

var B = function() {};
// inherit from A
B.prototype = new A;

x = new B;
y = new B;

$('#hello').text(x.Increment() + " - " + y.Increment());​
</code></pre>

<p>This outputs <code>1 - 2</code> (test it on <a href="http://jsbin.com/ateci3/2/edit" rel="nofollow">JSBin</a>), while I fully expected the result to be <code>1 - 1</code>, since I wanted two separate objects.</p>

<p>How can I make sure that the <code>A</code> object isn't shared object between multiple instances of <code>B</code>?</p>

<p><strong>Update</strong>: <a href="http://robertnyman.com/2008/10/21/javascript-inheritance-experimenting-with-syntax-alternatives-and-private-variables/" rel="nofollow">This article</a> highlights some of the issues:</p>

<blockquote>
  <p>The problem is that the scope each approach uses to create a private variable, which works fine, is also the closure, in action, that results in if you change a private variable for one object instance, it is being changed for all. I.e. it’s more like a private static property, than an actual private variable.</p>
  
  <p>So, if you want to have something private, more like a non-public constant, any of the above approaches is good, but not for actual private variables. Private variables only work really well with singleton objects in JavaScript.</p>
</blockquote>

<p><strong>Solution</strong>: As per BGerrissen's answer, changing the declaration of <code>B</code> and leaving of the prototype works as intended:</p>

<pre><code>var B = function() { A.apply(this, arguments); };
</code></pre>
