Constructor question

Tell us what’s happening:
I’m mostly concerned about the explanation in "ES6: Use getters and setters to Control Access to an Object
" in the example given the constructor looks as following:

class Book {
constructor(author) {
this._author = author;
}

why is “this._author” being used rather than just “this.author”? Could someone please help me clarify what’s going on… Thank you!

It’s a convention to indicate that the author property is private. JavaScript classes do not have private properties, so developers normally indicate fields that should not be accessed outside of the class by using an underscore - this._myPrivateProperty = 'foo';

It’s just saying that when this class is instantiated, you’re not supposed to use that property directly; it doesn’t stop you using myBook._author, it’s just to remind you that you shouldn’t do that.

2 Likes

@DanCouper is exactly correct. Can’t offer any other additional explanations as he covered it completely.

Then why did you reply? @hbar1st