In JavaScript, define a class with a property that shares the same data type

I am facing a scenario where I need to define a property within a class that is an instance of the same class. Here's an example:

class Example {

  constructor() {
    this.property = new Example();
  }

}

const e = new Example();

However, I keep encountering the error Maximum call stack size exceeded. Is there a solution to this issue?

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Occasionally I encounter the message: "Error: Server unexpectedly terminated with status 1."

I created an automated test to check the login page, with testing data stored in a JSON file. Here is the code in index.js: const fs = require("fs"); fs.writeFileSync("testReport.json", "{}", "utf-8"); const { login } = require("./tests/login"); const au ...

PHP - Issue with submitting form data using $_POST from within a Div text container

Having some trouble with the submission of the "about_me_container" div in my form using $_POST. I know that divs are not typically used with $_POST, so I tried changing the div to input type="text" and textarea but it still won't work. I also attempt ...

Secure animated boxes with jQuery for showing and hiding - indestructible!

My goal is to create a dynamic effect where the content box on a page changes upon hover. Initially, the box displays a heading (or image, or other element). Upon hovering over the box, the original content fades out while new content fades in and the box ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

React Native - Issue with Chart not updating correctly when new data is added

I'm struggling to create a dynamic chart using the Victory-Native library (click here for documentation). The goal is to modify the chart after pressing the "Get Data" button, but I've encountered a problem that has me stumped after hours of att ...

Verifying dynamic number inputs generated using JavaScript values and calculating the total with a MutationObserver

Preamble: I've referenced Diego's answer on dynamic field JS creation and Anthony Awuley's answer on MutationObserver for the created fields. After extensive searching, I found a solution that meets my needs, but it feels somewhat bulky des ...

Guide to converting JSON data into object structures

Question - How do I convert JSON data into objects? You can find the JSON data here Details - After successfully connecting to the API and retrieving the JSON data, I am looking to map two arrays data.hourly.time[] and data.hourly.temperature_2m[] into a ...

What is preventing the buttons from filling the entire space of the parent element in this case?

https://i.stack.imgur.com/kbiWi.png I'm trying to figure out how to make the Repos and Stars buttons fill the entire height of their parent container, similar to the Github icon. Unfortunately, the code below is not achieving this effect. I attempted ...

Issue with NPM's manual review process following recent package updates

Upon downloading node-sass, I encountered the following warning message: "found 9 vulnerabilities (4 moderate, 5 high) in 1869 scanned packages. 9 vulnerabilities require manual review. See the full report for details." Despite attempting to manually insta ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

React component failing to update when props change

After loading correctly, my react component fails to re-render when props change. Despite the fact that render() is being called and the list array contains the correct data according to console.log(list), the page does not refresh. Adding a setState in co ...

A step-by-step guide on utilizing the v-for index loop to showcase a nested JSON array

My JSON Array has the following structure: items: [ { ID: 11, UserID: "test.com", UserRole: "user", timeStamp: "2021-03-23T15:54:02.125578", dialogs: [ { "Bot" ...

Tips on declaring an object with a nested array of objects in TypeScript

In my code, I have defined two classes. One is called Stuff and the other is called Thing. class Stuff { constructor() { } things: Thing[] = []; name: string; } class Thing { constructor() { } active: boolean; } As I was working on my applicat ...

Is there a way for me to determine if there are elements in one object array that exist in another object

Is there a method to check if two object arrays have any common elements, and if so, find the intersecting object? Similar to a Contains function. For instance, in the provided example, ProductId3 in Object Array 1 is also present in Object Array 2. I&apo ...

Remove a file using Mongoose and Express by simply pressing a button

Trying to delete a connected account using Express and Mongoose. When the user clicks on a button (confirming their desire to delete their account), I want their account to be removed from my user's collection. HTML code snippet: <div class=" ...

Fetching data from external sources using the MongoDB copy item function

Here is an example of an array: "data": [ { "photo": "no-photo.jpg", "_id": "5e9aabd9c975a10a7ee48476", "title": "Title", "description": "Description", "phone": "77477926783", ...

Confirming the outcome of an unawaited asynchronous function in JavaScript

Consider the code snippet below for creating fake accounts: export const accounts = []; export const emails = []; export async function createAccount(name, email) { accounts.push({name, email}); void sendEmail(email); } async function sendEmail(e ...

Executing asynchronous function in Angular using Typescript

My team and I are new to Angular and we are facing a challenge with invoking methods in sequence and returning a value. The issue is that the return statement is being executed before the completion of the execution process. We have tried various approac ...

"Underscores in an array of primary keys serve as markers for

I want to filter a list of objects using underscore based on their primary key being included in a specific array of primary keys. list = [object{pk: 1}, object{pk: 2}, object{pk: 3}] primary_key_list = [1,2] The desired outcome is to return [object{pk: ...

Is there a way to assign a null value to an empty material UI text field when submitting the form, rather than an empty string?

One issue I am facing is that the default value of the text field is zero, but when I submit the form, the value of the text field becomes an empty string instead. This is not the intended behavior as I want the value to remain zero in the end. How can I r ...