JavaScript classes with getter and setter cause RangeError: Maximum call stack size exceeded

Jannis Lehmann picture Jannis Lehmann · Jul 17, 2015 · Viewed 16.5k times · Source

I am currently experimenting with ECMA6 classes. My current class looks like the following

class Player {
  constructor(id) {
    this.id = id;
    this.cash = 350;
  }

  get cash() {
    return this.cash;
  }

  set cash(value) { // line 19
    this.cash = value; // line 20
  }
};

When I am now creating a new Object by calling let playerObject = new Player(1); I receive the following error

...\node_modules\mysql\lib\protocol\Parser.js:82
        throw err;
              ^
RangeError: Maximum call stack size exceeded
    at Player.cash (player.js:19:11)
    at Player.cash (player.js:20:15)
    at Player.cash (player.js:20:15)
    at Player.cash (player.js:20:15)
    at Player.cash (player.js:20:15)
    at Player.cash (player.js:20:15)
    at Player.cash (player.js:20:15)
    at Player.cash (player.js:20:15)
    at Player.cash (player.js:20:15)
    at Player.cash (player.js:20:15)
Press enter to exit

What does this have to do with the mysql library? Why does the error is multiple times in the same line? I am only calling it once.

Answer

Greg Burghardt picture Greg Burghardt · Jul 17, 2015

Your "cash" setter calls the "cash" setter, which calls the "cash" setter, which calls the "cash" setter...

Accessing the property setter by its own name inside the setter creates an infinite recursive function call.