Use getters and setters to Control Access to an Object : Underline with/without author

Use getters and setters to Control Access to an Object : Underline with/without author
0

#1

Hello!

I have a question about the example.

  1. Why are there “author” and “_author”?
    What is underline for?
  2. I am using CodePen to check the code.
    But it doesn’t overwrite the properties of lol.writer with this code -> lol.writer = ‘wut’;
    Is it because I am using CodePen or wrong code?

Thank you your help in advance!!

class Book {
  constructor(author) {
    this._author = author;
  }
  // getter
  get writer(){
    return this._author;
  }
  // setter
  set writer(updatedAuthor){
    this._author = updatedAuthor;
  }
}
const lol = new Book('anonymous');
console.log(lol.writer);  // anonymous
**lol.writer = 'wut';**
**console.log(lol.writer);  // wut**

#2

It is just a way to clarify the difference between the local variable author and the property referencing the local variable value of author. The underscore character is just another valid character which can be used in variable names and/or property names.

The same code you have above should work on Codepen. I would need to see the pen code to tell you why it does not work. Can you provide a link to the pen in question?


#3

about the underscore…

It is just a way to clarify the difference between the local variable author and the property referencing the local variable value of author. The underscore character is just another valid character which can be used in variable names and/or property names.

Then is it mandatory to use underscore? I think i don’t fully understand this, and is a pitty that this is not covered in the lesson


#4

No, it is not. You could easily write the following and everything would work fine.

class Book {
  constructor(author) {
    this.author = author;
  }
  // getter
  get writer(){
    return this.author;
  }
  // setter
  set writer(updatedAuthor){
    this.author = updatedAuthor;
  }
}

Where you can really see the benefit of using the underscore character, is if you want use writer property. You can not reference this.writer because that is the same name as the getter/setter, but you could reference this._writer. See the following code for an example.

class Book {
  constructor(author) {
    this._writer = author;
  }
  // getter
  get writer(){
    return this._writer;
  }
  // setter
  set writer(updatedAuthor){
    this._writer = updatedAuthor;
  }
}

The use of the underscore character is a naming convention practice to distinguish between private member variables (the ones with the underscore) to keep them separated from methods and public properties (the ones you want others to actually reference in the code).