1

According to Martin, this syntax can be used to define a class in nodeJS:

class Person {
  constructor() {
    this.id = 'id_1';
  }
  set name(name) {
    this._name = name;
  }
  get name() {
    return this._name;
}

usage:

myPerson.name = "Saul"; // save the value in `_name` variable.

Slight problem with this convention is that calling JSON.stringify(myPerson) will print the following:

{
  "_name": "Saul"
} 

But if I remove the underline from the setter function, and write it as the following:

  set name(name) {
    this.name = name;
  }

the setter function will recursively call itself forever. So is there no way of using this nice getter-setter syntax, and still use the name property? I'm running nodejs.

Makan
  • 2,508
  • 4
  • 24
  • 39

1 Answers1

1

I dont see a problem at all here. If you deserialize it, it works as expected:

 const saul = Object.assign(new Person, JSON.parse('{"_name": "Saul"}'));
 console.log(saul.name);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    The problem is that JS here (and any big system I imagine) is only part of the system. And all parts need to deliver the agreed properties. Or is underlining beginning of properties a cross-language treat? – Makan Apr 03 '18 at 19:13
  • @makan good point. But then the dupe provides a good solution for this – Jonas Wilms Apr 03 '18 at 19:16