Reputation: 6844
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
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