0

I write javascript all day, but I have a different style than others. I was curious as to what are the differences in javascript in the 2 different implementations.

var ClassA = function(){
    var _value = 0;
    this.getValue = function(){ return _value; }
}

vs

var ClassB = function(){
    this._value = 0;
}
ClassB.prototype.getValue = function(){ return this._value; }

I see why based on javascript, prototypes would be used in inheritance. I like it, but i dont like values being publicly available.

For example, when i instantiate ClassB, you can investigate and see _value inside it. This makes it possible to be modified.

So, how would i go about making a prototype typed function like ClassB but hiding the properties of the object so they cant be changed, or logged, similar to ClassA

Edit I did try to create ClassB without using this, but _value was not recognized in getValue

Fallenreaper
  • 10,222
  • 12
  • 66
  • 129

1 Answers1

1
    var ClassA = function(){
        var _value = 0;
        this.getValue = function(){ return _value; }
    }


  ClassA.prototype.greatGetValue = function() { return this.getValue(); };
Oxi
  • 2,918
  • 17
  • 28
  • So a workaround would be to create setters and getters for the variables and then only reference them there. I like this answer a lot. I dont like the idea of someone changing arb variables, but this would allow you to implement controls such that if they were to change a variable with the function, it would update anything which correlates respectively. – Fallenreaper Jan 12 '16 at 16:37