Using JavaScript, include a child class into a parent class

I am facing an issue with my class hierarchy, which includes classes like Parent, Child1 (which extends Parent), and Child2. Parent contains an array of child items, but importing Child1 and Child2 into Parent leads to circular dependencies and errors when trying to create instances of Child1 or Child2.

The error message encountered is:

TypeError: Super expression must either be null or a function

What are the possible solutions to resolve this issue?

For better understanding, consider the following structure:

parent.js

export default class Parent {
    itemArray = []
}

child1.js

import Parent from "./parent.js"
export default class Child1 extends Parent {
}

child2.js

import Parent from "./parent.js"
export default class Child2 extends Parent {
}

The itemArray stores instances of either Child1 or Child2 recursively.

Now, I need to annotate the itemArray in parent.js as follows:

parent.js

import Child1 from "./child1"
import Child2 from "./child2"

export default class Parent {
    @Types(() => [Child1, Child2])
    itemArray = []
}

This annotation ensures that the correct class is assigned to each item in the array during object construction. However, the main question remains:

How can I structure my code to avoid breaking the entire hierarchy?

Answer №1

The solution presented is straightforward and easily comprehensible. It involves organizing classes hierarchically in a separate module.

// internal.js (New Js File)
// This module handles the import and export of classes
// Parent and Child classes will import classes from this module.

export { Parent } from "./parent.js";
export { Child1 } from "./child1.js";
export { Child2 } from "./child2.js";

You can then import the required class from 'internal.js'. For instance:

// parent.js

import { Child1 } from "./internal.js";
import { Child2 } from "./internal.js";

export class Parent {
     // @Types annotation method here..
     itemArray = [];
}

Output:

// index.js file for outputting the result

import { Parent } from "./internal.js";
import { Child1 } from "./internal.js";
import { Child2 } from "./internal.js";

var child1 = new Child1();
var child2 = new Child2();
var parent = new Parent();

parent.itemArray.push(child1);
parent.itemArray.push(child2);

console.log(parent.itemArray.length); // output will be '2'

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

Displaying images retrieved from firebase on a React.js application

Currently, I am attempting to retrieve images from Firebase storage and then exhibit them in a React component. As a newcomer to React/Javascript, I find it challenging to grasp the asynchronous nature of React/JS. The issue I'm facing is that althoug ...

React Router integration problem with Semantic UI React

Just diving into ReactJS and encountering a problem with using "Menu.Item" (from Semantic UI React) and React Router. I won't include my imports here, but rest assured they are all set up correctly. The constructor in my "App.jsx" looks like this: ...

Let's explore further - delving into JSON & array manipulation using the foreach loop in Pure JavaScript

Although I have some experience with Java Script, I still consider myself a beginner in certain areas, particularly when it comes to accessing JSON objects and arrays. I've tried various syntax and options for accessing arrays using [], but so far, I ...

Drop Down Automation with Selenium IDE

Currently in the process of automating a User Acceptance Testing (UAT) for a software project at my company. I've completed all the typical tasks like recording actions and clicking on buttons, but ran into an issue with a drop-down menu. The problem ...

Using AngularJS ng-model to select options in a dropdown menu with WebDriver

In the following code snippet, an AngularJS based dropdown menu is implemented: <select _ngcontent-c1="" class="form-control ng-pristine ng-valid ng-touched"> After opening the list, I attempted to select a variable from this list using the code be ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

Stop the unnecessary reloading of Ajax data when navigating back using the browser's back button in Chrome and Internet Explorer

I am currently designing a website where the main page showcases the latest 10 blog entries. As I scroll down and approach the end of the last item on the screen, another set of 10 blog entries automatically load through infinite scrolling. If a user clic ...

Is there a way to make the text on my Bootstrap carousel come alive with animation effects?

My website features a Bootstrap Carousel with three elements structured like this: <a><img data-src="img" alt="Third slide" src="img"> </a> <div class="carousel-caption"> <h2> <u ...

ajax is providing identical data when called too frequently

Using my barcode scanner triggers the function below, but scanning multiple barcodes quickly results in duplicate data being processed. The issue seems to be related to the async setting - when it's false, the process slows down significantly. Is the ...

JavaScript code for iframe auto resizing is not functioning properly on Firefox browser

I have implemented a script to automatically resize the height and width of an iframe based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newh ...

The input value is displaying one value, but the output is showing a different value

I am encountering a unique issue and could really use some assistance. <input class="testVal" type="number" id="GT_FIRING_TEMPERATURE" value="-17" name="degC" onchange="angular.element(this).scope().unitConversion(value,name, id)"> Despite the valu ...

Is it necessary to download all npm packages when starting a new project?

I recently started learning about npm packages and node. I noticed that when installing packages, they create numerous folders in the "node modules" directory. This got me thinking - when starting a new project, do I need to re-install all these packages ...

Mixed Protocol Error (HTTP/HTTPS)

I'm experiencing a mixed content error on my website, as it is using both http and https protocols. Chrome console displays the following error: Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure XMLHttpReques ...

What methods are commonly used to calculate the bitsPerSecond rate for media recording?

Is there a specific formula that combines frames per second and resolution to determine the bits per second for video encoding? I'm struggling to figure out the appropriate values to use for specifying the bits per second for 720p, 1080p, and 4k video ...

Executing a JavaScript Function in the Background using Cordova

Despite the numerous questions and plugins available on this topic, finding a solution has proven to be elusive for me. The most highly recommended plugin for this issue can be found here. My goal is to run MyService in the background, subscribe to the ON ...

Waiting for all promises to resolve: A step-by-step guide

I need to make two different API calls and perform calculations based on the results of both. To wait for both promises to resolve, I am using Promise.all(). const getHashTagList = async () => { loader.start(); try { await getAllHashTag ...

Creating virtual hover effects on Android browsers for touch events

My Wordpress website is currently utilizing Superfish 1.5.4 to display menu items. The menu on my site includes several main menu items, which are clickable pages, and hovering over these main items should reveal sub-menu options. When I hover over a mai ...

Data within React/Next.js will remain unchanged even after a link has been clicked

When using Next.js and clicking on a Link, the new page URL will open as "/component/product". However, the product data is not updated in the Redux store. The page needs to be refreshed in order to update the state data. import Link from "n ...

Having trouble displaying a set of data points in a React component

Exploring React, I have built a test app and performed an API call to fetch a large JSON object. After breaking it down into 10 arrays with 3 props each, I am now facing a challenge in sending this data to another component. Despite being able to log the ...

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...