一尘不染

具有getter和setter的JavaScript类导致RangeError:超出最大调用堆栈大小

node.js

我目前正在尝试ECMA6类。我当前的课程如下

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
  }
};

当我现在通过调用创建新对象时,let playerObject = new Player(1);出现以下错误

...\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

这与mysql库有什么关系?为什么同一行中的错误多次出现?我只叫一次。


阅读 263

收藏
2020-07-07

共1个答案

一尘不染

您的“现金”设置器称为“现金”设置器,称为“现金”设置器,称为“现金”设置器…

在设置器中通过其自己的名称访问属性设置器会创建一个无限的递归函数调用。

2020-07-07