undefined
undefined

Reputation: 6844

JS create property in a class which is the same type

I have a use case where I want to create a property in a class which is a new instance of the current class. For example:

class Test {

  constructor() {
    this.prop = new Test()
  }

}

const t = new Test();

The problem is that I get Maximum call stack size exceeded. There is any way to do it?

Upvotes: 0

Views: 34

Answers (1)

trincot
trincot

Reputation: 349954

Indeed, the constructor is called again when you do new Test(), so you get an endless call of the constructor.

You probably should do this one by one, and call a method explicitly when you want to "deepen" the object structure with a next instance of Test, like so:

class Test {    
  constructor() {
    this.child = undefined;
  }
  createChild() {
    return this.child = new Test();
  }
}

const t = new Test();
const child = t.createChild();
const grandChild = child.createChild();
// ...etc

Now you control how deeply nested this structure should become. Maybe you just want one level deep? Then just call createChild only on the first instance.

Upvotes: 2

Related Questions