0

Lets say I have an object with a getter and a setter.

const obj = {
  a: 0,
  get a(){
    return this.a;
  }
}

I would get an error Maximum call stack size exceeded at Object.get a [as a]. I could name the a variable something different but then it gets confusing after a while.

I could prefix it with an underscore or something like this:

const obj = {
  _a: 0,
  get a(){
    return this._a;
  }
}

I was wondering if there is an industry standard for handling this? Is using underscores not the right approach because they are symbolic of other things? What is the recommended approach for handling this or is it one of those things that is up to the developer?

I just don't want to go down the path of doing this the wrong way and can't really find a definitive answer on the matter.

Thanks.

user3331344
  • 291
  • 3
  • 16
  • 1
    What are you trying to solve by trying to use a getter ? These properties are not private anyways, anybody can do `obj.a` directly. – ajobi Apr 19 '20 at 19:07
  • Data validation is the first thing that comes to mind. Even if the underlaying variable could be used, you shouldn't, this is usually as part of the documentation regarding a class/component. Getter/setter have great regardless of member accessors features. – Radu Diță Apr 19 '20 at 19:10
  • @ajobi this is just for ease of demonstration I am creating a system to listen for changes in the variable. – user3331344 Apr 19 '20 at 19:10
  • AFAIK, No. There's no way to name the setter and the getter the same name of your property. – rksh1997 Apr 19 '20 at 19:15
  • @RashadKokash I obviously know I cant name them the same thing. That is the entire reason for the question. – user3331344 Apr 19 '20 at 19:18
  • In my opinion the *best* way of setting that up is with a Symbol as the property "name", and doing it in such a way that the getter/setter functions are the only things with access to the Symbol value via using a closure. – Pointy Apr 19 '20 at 20:37

1 Answers1

2

Your first example doesn't work, because the getter named a will end up being the only property on your object. When you call this.a you're actually calling the getter again and so you end up with a stackoverflow.

Using _ as prefix for underlaying variables is perfectly fine. This actually lines up with other languages.

Radu Diță
  • 8,910
  • 1
  • 18
  • 27
  • Do you think the underscore is a bit misleading because it usually signifies a private variable or function. – user3331344 Apr 19 '20 at 19:20
  • Well, if you declare getters/setter you expect it to not be accessed directly, this is in a way wishing for it to be private. – Radu Diță Apr 19 '20 at 19:21