0
class User {
      constructor(name) {
           this.name = name;
      }
      get name() { **// line A**
            return **this._name**; // if change _name to name, error occurs
      }
      set name(value) { **// line B**
             if (value.length < 4) {
                 alert("LALALAL");
                 return;
              }
             **this._name** = value; // if change _name to name, error occurs
      }
   }
   let user = new User("John");
   alert(user.name); // John
   user = new User("zxcvasd"); // zxcvasd
   alert(user.name);

Hello, this is an example I found online and I am getting the error "Uncaught RangeError: Maximum call stack size exceeded" in line A/B if I changed this._name to this.name. Not quite sure what causes the problem as what I found in this post Underscore prefix for property and method names in JavaScript says _name is just a convention and doesn't have any special meaning?
Any help is appreciated..
Thank you

1 Answers1

3

When you declare a method as get name(), with you type object.name;, it is replaced by object.name(). This is how a getter works.

So if you write

get name() {
    return this.name;
}

You are writing this :

get name() {
    return this.name();
}

And you have an infinite recursive function. So you have a stack overflow.

This is the same for set name(value) and this.name = value;.

Magus
  • 13,609
  • 2
  • 31
  • 47
  • ohhhh. Would that mean if I replace this.name with this._name ----> it would only call getter/setter once because compiler can;t find _name() method ? Thank you – coolKids123321 Jan 04 '19 at 16:46