It is important to note that each time you use new Test()
, the constructor will be called again, leading to an endless loop of constructor calls.
To avoid this issue, consider creating instances one by one and explicitly calling a method when you want to add another level to the object structure using a new instance of Test
. Here's an example:
class Test {
constructor() {
this.child = undefined;
}
createChild() {
return this.child = new Test();
}
}
const t = new Test();
const child = t.createChild();
const grandChild = child.createChild();
// ...continue as needed
By following this approach, you have control over how deep the nested structure should go. If you only need one level of nesting, simply call createChild
on the initial instance.