skip to Main Content

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


  1. 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) sets this._name = value;.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search