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?

2
  • btw, console.log is usually a much better way to print values for debugging than alert. Commented Mar 19, 2014 at 18:41
  • Do not use new function()! Commented Mar 19, 2014 at 18:43

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

2 Comments

is this the only way I checked and works great but apparently prop A should be explicitly defined with getter and setter?
@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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.