8

I'm dabbling with the new ES6 Class keyword and I have a funky scenario that gives me some infinite loop and eventually Maximum call stack size exceeded.

Here's my class:

'use strict';

class Group {

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

}

module.exports = Group;

and I'm calling it with this mocha test:

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

    });

  });

});

When I run my mocha test I get this printout:

 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)

What is causing this infinite loop and how can i get around it?

FYI I'm on node.js 5.1.0

Catfish
  • 18,876
  • 54
  • 209
  • 353
  • 1
    You currently have a method called `name`, as well as a property called `name`. Try changing the method to `setName`. – jperezov Dec 07 '15 at 22:28
  • Actually, he's using a property with a setter which calls itself recursively. If you mean to have a backing field, name it differently. – Ixonal Dec 07 '15 at 22:29
  • Ahh i'm an idiot. changing `this.name` to `this._name` works. – Catfish Dec 07 '15 at 22:30

1 Answers1

18

Your setter property is recursively setting itself. Try something more along the lines of this...

class Group {

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

  get name() {
    return this._name;
  }

}
Ixonal
  • 616
  • 8
  • 18