【问题标题】:ES6 Class Maximum call stack size exceeded [duplicate]ES6类超过最大调用堆栈大小[重复]
【发布时间】:2016-03-12 16:43:21
【问题描述】:

我正在涉足新的 ES6 Class 关键字,我有一个时髦的场景,它给了我一些无限循环,最终给了我Maximum call stack size exceeded

这是我的课:

'use strict';

class Group {

 set name(newName) {
    this.name = newName;
  }

}

module.exports = Group;

我用这个摩卡测试来称呼它:

'use strict';

const expect = require('chai').expect;

describe('Group model', function() {

  var Group;

  it('should not blow up when requiring', function() {
     Group = require('../../models/group');
     expect(Group).to.not.be.undefined;
  });

  describe('create()', function() {
    it('should fail with no parameters', function() {
      const expected = new Error();

      var group = new Group();
      //group.name('myName');
      group.name = 'myName';

    });

  });

});

当我运行 mocha 测试时,我得到了这个打印输出:

 1) Group model create() should fail with no parameters:
     RangeError: Maximum call stack size exceeded
      at onwrite (_stream_writable.js:335:15)
      at WritableState.onwrite (_stream_writable.js:89:5)
      at WriteStream.Socket._writeGeneric (net.js:684:5)
      at WriteStream.Socket._write (net.js:694:8)
      at doWrite (_stream_writable.js:292:12)
      at writeOrBuffer (_stream_writable.js:278:5)
      at WriteStream.Writable.write (_stream_writable.js:207:11)
      at WriteStream.Socket.write (net.js:618:40)
      at Console.log (console.js:36:16)
      at Group.name (models/group.js:122:13)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)
      at Group.name (models/group.js:123:15)

是什么导致了这个无限循环,我该如何解决?

仅供参考,我使用的是 node.js 5.1.0

【问题讨论】:

  • 您当前有一个名为name 的方法,以及一个名为name 的属性。尝试将方法更改为setName
  • 实际上,他正在使用带有 setter 的属性,该 setter 递归调用自身。如果您想拥有一个支持字段,请以不同的方式命名。
  • 啊,我是个白痴。将 this.name 更改为 this._name 有效。

标签: javascript node.js class oop ecmascript-6


【解决方案1】:

您的 setter 属性正在递归地设置自己。尝试更多类似的东西......

class Group {

 set name(newName) {
    this._name = newName;
  }

  get name() {
    return this._name;
  }

}

【讨论】:

  • 这只是头脑麻木。他们为什么要这样设计?
猜你喜欢
  • 2020-01-05
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 2017-02-04
  • 2014-08-19
  • 1970-01-01
  • 2015-10-24
  • 2015-12-29
相关资源
最近更新 更多