0

Is this a good way to make a private property in JavaScript production code? It should be equivalent of "private" in Java because objects which inherit from below should not have access to foo and boo. How to make method or property "protected"?

var Constructor = function(val) {
  var foo = val //private property

  var boo = function() {} //private method

  this.getFoo = function() {
    return foo
  }
};

var obj = new Constructor(1)
var obj2 = new Constructor(2)

console.log(obj.getFoo())
console.log(obj2.getFoo())

Regards

Robin Mackenzie
  • 18,801
  • 7
  • 38
  • 56
Michal Bialek
  • 499
  • 1
  • 10
  • 26
  • 1
    This is exactly how you make things private in JavaScript also for better reading usually for private things you add an underscore to the name. But thats just a community standart not required. Some Frameworks have this adapted tho like Polymer. for instance: var _foo = val; – Pascal L. Jun 17 '17 at 14:51
  • Possible duplicate of [JavaScript private methods](https://stackoverflow.com/questions/55611/javascript-private-methods) – styfle Jun 17 '17 at 16:01
  • Related: [Private properties in JavaScript ES6 classes](https://stackoverflow.com/q/22156326/266535) – styfle Jun 17 '17 at 16:05

0 Answers0