0
var pagger = new function () {

var _a = 1;
var _b = 2;

function add() {
    return _a + _b;
}
return {
    A: _a,
    B: _b,
    Add: add

        };
};

//return 1
alert(pagger.A);
pagger.A=2; 
pagger.B=2;

//return 2
alert(pagger.A);


//return 3
alert(pagger.Add());

If I use this way to create object A and B are accessor for private _a and _b but if I try to change property _a trough A, function Add not take that in account. Is there way to make this work?

plamtod
  • 79
  • 3
  • 9

1 Answers1

1

You need to use getters and setters:

return {
    getA: function(){ return _a },
    setA: function(x){ _a = x },
    //...
}

Actually, the .A field is not an acessor to a private variable like in other OO languages. Its just a hashtable field that initially points to what _a was currently stored. If you mutate _a or .A afterwards, one will not interfere with the other.


A simpler alternative would be to make those fields public isntead of wrapping some inner variables:

function make_pager(){
   return {
       A : 1,
       B : 2,
       Add: function(){
           //use the dynamically scoped "this" instead 
           //of lexical variables
           return this.A + this.B
       }
   }
}

var pager = make_pager();

pager.A = 10;
console.log(pager.Add());
hugomg
  • 68,213
  • 24
  • 160
  • 246
  • is this the only way I checked and works great but apparently prop A should be explicitly defined with getter and setter? – plamtod Mar 19 '14 at 18:34
  • @plamtod: If you want private variables then getters and setters are the only way. However, you could always make those fields public and store the info in a single place (see my edit). – hugomg Mar 19 '14 at 18:41