Constructor question

Constructor question
0.0 0

#1

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!


#2

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.


#3

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


#4

Then why did you reply? @hbar1st