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.