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?
Your Problem is that you redefine
Foo.prototype.vGet
every time you construct an new instance ofFoo
. The prototype is shared between all instances ofFoo
, but your redefinedvGet
function contains a reference the_v
variable of the last constructed instance ofFoo
.The solution is either to change
Foo.prototype.vGet = ...
toFoo.vGet
and hence create a new function every time. Or to move the assignment outside of the constructor function and for example usethis._v
instead of_v
, which weakens your encapsulation.