JavaScript: Private members overwritten by another instance

49 views Asked by At

I have this:

var Foo = function( v )
{
  /* Private member for shorthand prototyping */
  var _prototype = Foo.prototype;

  /* Private member */
  var _v = null;

  /* Public getter */
  _prototype.vGet = function( )
  {
    v = _v;
    return v;
  };

  /* Private setter */
  var vSet = function( v )
  {
    _v = v;
  };

  /* Constructor closure */
  ( function( v )
  {
    vSet( v );
  } )( v );
};

var f1 = new Foo( 10 );
console.log( 'f1::' + f1.vGet( ) );  /* f1::10 */
var f2 = new Foo( 20 );
console.log( 'f2::' + f2.vGet( ) );  /* f2::20 */
console.log( 'f1::' + f1.vGet( ) );  /* f1::20 */

So my problem is obvious. After creating the second instance of Foo in f2, f1._v is changing, too.

I choose this pattern with private setters to prevent members to be changed unwanted from outside the class itself.

By what I read about the prototyping this behaviour should not occur. But oviously my private member is used uniquely by several instances. So what did I misunderstood?

1

There are 1 answers

1
gregor On BEST ANSWER

Your Problem is that you redefine Foo.prototype.vGet every time you construct an new instance of Foo. The prototype is shared between all instances of Foo, but your redefined vGet function contains a reference the _v variable of the last constructed instance of Foo.

The solution is either to change Foo.prototype.vGet = ... to Foo.vGet and hence create a new function every time. Or to move the assignment outside of the constructor function and for example use this._v instead of _v, which weakens your encapsulation.