5

I'm having problem with private variables in JavaScript's Revealing Prototype Pattern. I can't figure out how can I have private variables that are used in several different functions inside shared (singleton) prototype, without exposing them. Here is the example of what I mean in JSFiddle.

The problem is in using var v versus this.v. First one messes the state of all instances, but second is publicly visible. Is there a way to have v private, and preserve its state for each individual instance?

Janez Lukan
  • 1,439
  • 1
  • 12
  • 28
  • 1
    yes, you can have instance specific "private" variables in JavaScript but any function using those will have to be defined in the body of the constructor function as well (see Paul's answer). This means more cpu and memory is needed to create instances. If you have a good enough reason to write code that consumes more resources then go for it. Personally I never found a good enough reason for it and would agree with Paul on sticking an underscore in front of the variable to indicate it's intended as private. More info on prototype, inheritance ... http://stackoverflow.com/a/16063711/1641941 – HMR Nov 03 '13 at 11:44

1 Answers1

7

There is not a way to do that with the revealing prototype pattern.

You can only do that with something like this:

function MyClass() {
    var v = 1;
    this.getV = function() {
        return v;
    };
}

And that's why there are some die-hard enthusiasts for this kind of approach.

Personal option: Stick an underscore in front of it, and putting it on the object: this._v. Don't fight JavaScript; use it.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
  • Seems like only get private members are possible. As soon as there's a need for setter, it must be publicly visible, and there's no sense in having `this.setV = function(value) {...`. I guess I'll live with `this._v` ;) – Janez Lukan Nov 03 '13 at 15:50
  • @lucky3, there *is* a use for a setter. Suppose you want to ensure that `v` is a positive number. `setV` would do that validation. – Paul Draper Nov 03 '13 at 19:06