I saw the below code at https://javascript.info/class
Its constructor is taking the name
parameter and assigning it to this.name
. Then in the getter named name
it is returning this._name
. Why does this code work even when the constructor is not using this._name
to set the value?
class User {
constructor(name) {
// invokes the setter
this.name = name;
}
get name() {
return this._name;
}
set name(value) {
if (value.length < 4) {
alert("Name is too short.");
return;
}
this._name = value;
}
}
let user = new User("John");
alert(user.name); // John
user = new User(""); // Name is too short.
2
Answers
The underscore is a normal character and doesn’t have a special meaning in JavaScript. You could replace it with
p
for private or something else.The property
this.name
has a getter and a setter.this.name = name;
in the constructor calls the setter. There is even a comment// invokes the setter
.The setter
set name(value)
setsthis._name = value;
.The get and set keywords mean those funcs are invoked automagically, so when you create the new User and call
alert(user.name)
, you’re accessing_name
and nevername
. You could rename_name
tofoo
or_foo
and it would work the same way.