There was a mistake while declaring a class and object in JavaScript

Below is my class declaration:

class Category {
  constructor(id, name, type, url) {
    this.id = id;
    this.name = name;
    this.type = type;
    this.url = url;
    this.assets = [];
  }

  set assets(value) {
    this.assets = value;
  }
}

To use it in my main class, I imported it as import Category from './beans';. I tried to create an object of this class using

let category = new Category("1", "2", "3", "4");

An error occurred:

undefined is not a constructor (evaluating 'new _beans.Category("1", "2", "3", "4")')

Is there a way to resolve this issue?


UPDATE: It appears that the error was caused by the presence of the assets declaration within the constructor of Category. After removing it, the code worked fine. Now, the question remains on how to store a variable in the Category class that can be initialized at a later time and not in the constructor.

Answer №1

When looking into how to store instance variables, it's important to note that in contrast to some programming languages, you cannot define instance variables outside of the constructor or another instance method in JavaScript. These variables must be set within the constructor, even if you don't have the values ready beforehand. For example:

class Product {
    constructor(id, name, price, description) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.description = description;
        this.reviews = [];
        this.customVar = null;
    }
    setCustomVar(customVar) {
        this.customVar = customVar;
    }
}

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

Authentication in JavaScript using JSON strings: two objects are being authenticated

Currently, I am in the process of authentication using $.ajax({ type: "GET", url: urlString, async: false, beforeSend: function(x) { }, dataType: "json", username: "<a href="/cdn-cgi/l/email-protection" class="__c ...

How to implement smooth scrolling to a specific div in Bootstrap 4

My experience with Bootstrap 4 has been somewhat puzzling as the scroll to div functionality seems to be working only on mobile phones or smaller screens. Below is the Javascript code I am using: <script> $(".navbar-nav li a").click(function(e ...

Sending information from ngRoute resolve to the controller

I am currently working on an application that utilizes ngRoute to create a Single Page Application. One of the requirements is to ensure that the view is not loaded until the data has been successfully fetched from the database. While I have managed to ach ...

Encountering the error message "do not mutate props directly" while also trying to render a button

Whenever I try to pass my prop to a component, I encounter an error message. The prop in question is used to display a button element in the payment section. However, there are certain components where this button should not be displayed. Unfortunately, wh ...

Is there a way to present a standard image in a circular format?

My goal is to transform a regular rectangle image into a rounded image. Can anyone provide guidance on how to achieve this transformation? (Credit for the image) ...

Issues have arisen with the loading of the Angular JS module

Whenever I try to add ng-app="adminApp" to the body in AngularJS, I always encounter this error. The error occurs during auto bootstrap. Uncaught Error: [$injector:modulerr] Failed to instantiate module adminApp due to: Error: [$injector:nomod] Module ...

Logging into the web application on Google Firebase is simple and secure

I've created a webpage called index.html as the main landing page for my Google Firebase Hosted Web app. This page features input boxes for the user's username and password, along with a button labeled LOGIN. When a user clicks the LOGIN button ...

A justifiable amount of concurrent, asynchronous ajax requests

I'm curious to know what most people think about the ideal number of simultaneous asynchronous ajax requests allowed. Personally, I try to limit my requests to just one in my web app. However, there are some instances where I need to send up to 4 req ...

Ensuring the correct mapping of keys and values in a TypeScript dictionary

Looking for guidance on dictionary conditions: dict = { "a": 1, "b" : 2 } I'm trying to create a condition that returns true if "a" is 1 and "b" is 2, extending to additional key-value pairs. Can anyone advis ...

What could be causing the prime factorization function to malfunction?

I have encountered an issue with a simple JavaScript function I created to factor down numbers into primes. The problem arises when the input number is the product of duplicate prime numbers, as the function does not include these duplicates in the array o ...

Can the lazy load script dependent on jQuery be utilized before the jquery.js script tag in the footer?

After receiving HTML from an AJAX callback, I noticed that there is a script tag for loading code that uses jQuery. However, I consistently encounter the error of jQuery being undefined. All scripts are connected before the closing </body> tag. Is ...

The dynamic pages specified by the graphql query in the gatsby-node.js file are not being generated by Gatsby.js as expected

Even after running gatsby clean followed by npm run develop, the issue persists... Several individuals familiar with the Gatsby framework have reviewed my gatsby-node.js file, but the problem remains puzzling... Below is a snippet of my gatsby-node.js fi ...

Guide to showcasing the most recent search history results upon clicking the search button in vuejs?

My JavaScript file is displayed below: <div v-bind:class="{'open':openSuggestion}" class="search-bar"> <input class="form-control bg-light-blue" id="SearchText" type="text" v-model="search" @keydown.enter = 'enter&ap ...

Shadow typing, also known as type over words, is a method where the

I am currently tackling a project focused on language acquisition, including German, Chinese, and more. We are encountering difficulties with one specific feature - the ability to display "ghost" text (in a very faint grey) for users to type over. With th ...

Could anyone assist me in resolving the error stating, "The 'Argument `where` of type UserWhereUniqueInput needs at least one of `id` arguments"?

Upon investigating, I inserted this console log to determine what data is being received: { username: 'aa', gender: 'Feminino', cargo: '2', email: 'a', password: 'a' } Lately, I've been facing this err ...

Issue with Fancybox's close button not being displayed when using a different template

On one of my pages, I'm trying to use two different FancyBox styles for different elements. To accomplish this, I have included the tpl option and made adjustments to the stylesheet. Here is what I currently have: $(document).ready(function() { $(".l ...

Invoke a Node.js script from a Spring Boot application to pass a Java object to the script. The script will modify the object and then return it back to the originating class

class Services { Address address = new Address(....); /* Invoke NodeJs script and pass address object In the js script modify address object var address = getAddress() Modify address object Return address obj ...

Organizing a Javascript project for development and production with the help of npm and grunt

I have been working on structuring the JavaScript files in my project. I opted to use NPM for managing modules and Grunt for concatenating and compressing js and css files for deployment purposes. Here is the current structure I am using: -[project root ...

Using Python Selenium to interact with elements on a web browser and make edits

Is there a way to modify an element in a web browser using Python 2.7 Selenium? Consider this element: <span id="some-random-number">100</span> While you can retrieve the text with: driver.find_element_by_id("some-random-number").text how c ...

When utilizing AngularJS, a parse error is triggered by array[ {{value}} ], but I prefer to overlook it

Within the controller, I have a selection list that is displayed like this: <select class="input form-control" id="animationTime" ng-options="item as item.label for item in aniCon.timeOptions track by item.id" ng-model="aniCon.popupTime" ...