0

How can a prototype method access private variables (values accessed via closures) in the constructor without exposing public getters and setters.

function User() {

     var value = 1;

     this.increment = function () {
         value++;
     };

     this.set = function (val) {
         value=val; 
    };
    this.get = function () {
         return value;
    };     
}

User.protptype.add = function (value) {
    this.set(this.get()+value);
}

How can I get rid of get() and set() and still have only one copy of add()?

The intent is to ensure that there is only one instance of the add() function and not one created for each object while that object being able to access the private variables in this case the value variable in the constructor.

Pavlo
  • 43,301
  • 14
  • 77
  • 113
Raj
  • 3,051
  • 6
  • 39
  • 57
  • 1
    possible duplicate of [javascript - accessing private member variables from prototype-defined functions](http://stackoverflow.com/questions/436120/javascript-accessing-private-member-variables-from-prototype-defined-functions) and [How to create private variable accessible to Prototype function?](http://stackoverflow.com/questions/6307684/how-to-create-private-variable-accessible-to-prototype-function). The second one has a workaround. – Raymond Chen Jun 08 '13 at 14:39

1 Answers1

2

Because the concept of private was never part of JavaScript thus there is no way to do so naturally. You are just "emulating" privates in JS.

The only way you can do it is to place the method declaration inside the constructor's scope so that it can see the "private" members. But this would mean duplicating the function on every instance, and the function lives on the instance, not on the prototype.

function User(){

  var value = 1;

  this.add = function(newValue){
    value += newValue;
  };

}
Joseph
  • 117,725
  • 30
  • 181
  • 234