skip to Main Content

I’m receiving maximum call stack size exceeded error on 2 identical defined classes, execept 1 is defining this.name and the other this._name. What is the difference in the 2 classes that’s causing one of them to return a class stack error?

class User {

    constructor(name) {
      // invokes the setter
      this.name = name;
    }
  
    get name() {
      return this._name;
    }
  
    set name(value) {
      if (value.length < 4) {
        console.log("Name is too short.");
        return;
      }
      this._name = value;
    }
  
  }
  
  let user = new User("John");
  console.log(user.name); // John
  
  user = new User(""); // Name is too short.

RangeError: Maximum call stack size exceeded


class User {

    constructor(name) {
      // invokes the setter
      this.name = name;
    }
  
    get name() {
      return this.name;
    }
  
    set name(value) {
      if (value.length < 4) {
        console.log("Name is too short.");
        return;
      }
      this.name = value;
    }
  
  }
  
  let user = new User("John");
  console.log(user.name); // John
  
  user = new User(""); // Name is too short.

2

Answers


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

    I believe this act as an infinite recursive function ..
    When you call

    console.log(user.name);
    

    It just endlessly call the getter.
    Same thing happening for the setter ..

    Login or Signup to reply.
  2. The first class defines this._name as a data property.
    When the constructor sets this.name, it is passed to the Setter, which sets the value of this._name to the value. When the getter is called now, it returns the value of this._name, which was set by the setter earlier.

    The second class only defines a getter and a setter for this.name.
    When the constructor attemts to set this.name to a value, the setter will also try to set this.name, which causes the setter to invoked, and the new instance of the setter is attempting to modify this.name again, and then the maximum recursion limit is exceeded like this. Same goes for the getter in the second class. It returns this.name thereby invoking itself, and this way, it fills up the stack to the maximum recursion limit.

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