What is writer()?

Hello,
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object

I didn’t found technical document about writer() methode.
Do you know where I can found it ?

It is not a standard JS method. It is defined in the class here:

  get writer() {
    return this._author;
  }

It is a “getter” function. It is like telling the class, “Hey, if anyone tries to access a property “writer” on an instance of this class, then call this function and use its return value.” Notice that the “writer” property is never defined.

Here:

console.log(novel.writer);

We access the property. JS says, “Hey, that property doesn’t exist, but I do see a getter - I’ll use that.”

Notice that there is also a “setter” for that property.

Why not just have a “writer” prop and use it normally? This allows you to “hide” various class properties so the user cannot access them directly. OK, technically older versions of JS, they still can access “_author”. The _ before the name is a common convention to let people know that it is meant to be private to the class, not accessed directly from outside the class. In some languages (and recent JS versions) you can enforce this with a private keyword.

Ok thank you very well kevin :wink:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.