You are unable to declare objects within an object of a Class in JavaScript

class B{
    item = {};
    item.name = "example";
}

let b = new B()

What is the reason behind not being able to define an object and add a property inside a class like this?

Answer №1

When defining instance fields using this syntax (outside of the constructor), keep in mind that you cannot mutate them. It's important not to mistake the = syntax for regular assignment, as it follows different rules. Here is an example of using this syntax:

class A {
    ["obj"] = {};
}

If you need to mutate fields or properties, you will have to do so within the constructor or another method. However, you are free to initialize the field with a complex object literal.

Note: To create an instance, remember to use the new keyword.

Therefore, you can either:

class A {
    obj = { x: 0 };
}

let a = new A();
console.log(a.obj.x);

Or you can:

class A {
    obj = {};
    constructor() {
        this.obj.x = 0;
    }
}

let a = new A();
console.log(a.obj.x);

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

Experiencing difficulties installing the MEAN stack

I've been attempting to set up the MEAN stack by following a tutorial on Bossable website. I'm using Webstorm and MongoDB for this installation. Unfortunately, I'm facing some issues and encountering errors. Every time I try to connect to l ...

Sequential invocations to console.log yield varying outcomes

So, I'm feeling a bit perplexed by this situation. (and maybe I'm missing something obvious but...) I have 2 consecutive calls to console.log. There is nothing else between them console.log($state); console.log($state.current); and here's ...

Order comments based on their category using vue.js

I have a component form with select filter: <template> <div class="form-group"> <select name="" v-model="filterRev" @change="filterReviews(filterRev)" class="form-control" id=""> <option ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

propagate the previous state using a variable

Currently, I am in the process of refactoring a codebase but have hit a roadblock. My main aim is to update the state when the onChange event of a select box occurs. Specifically, the parameter searchCriteria in my handleFilterChange function is set to in ...

retrieve the timestamp when a user initiates a keystroke

Seeking assistance from the community as I have been struggling with a problem for days now. Despite searching on Google and Stack Overflow, I haven't found a solution that works for me. My web application features an analog clock, and I need to capt ...

verification tool for a less file's syntax

Searching for a tool to validate a specific less file at the syntax level. The issue lies in the validator not recognizing dependencies or detecting declared mixins. Many existing less processors do not work due to missing dependencies that cannot be prov ...

The placeholder within my input moves up and down when switching the input type from password to text

Currently, I am encountering an issue with the styling of a standard input element in React. Specifically, the placeholder text moves up and down by about 2px when viewed on Chrome, while there are no problems on Safari. How can I go about resolving this i ...

Using Bootstrap4 to merge rows into a single column or apply rowspan in Bootstrap

Hey there, I have a specific requirement that I need help with. Check out the image here. I want to enable the LCM information box when the LCM checkbox is checked. Below is my code: <div class="panel-body "> <div class="c ...

Enhancing Numbers with JavaScript

What I'm Looking for: I have 5 counters on my webpage, each starting at 0 and counting upwards to different set values at varying speeds. For example, if I input the values of 10, 25, 1500, 400, and 500 in my variables, I want all counters to reach t ...

Using Node.js and Angular to Access Google Spreadsheet JSON Data Across Different Origins

Seeking to extract JSON data from a public Google Spreadsheets page, my initial attempt involved an AJAX call which successfully retrieved the data but I struggled with saving it to my $scope. Switching to $http.get led me to encounter cross-origin reques ...

Ways to verify if a firebase timestamp surpasses the present date

Would you help me with comparing a timestamp field with the current date using JavaScript? This is what I have tried so far: // Initialize an empty array to store documents let myDocs = []; // Call the getDocs function and handle the response await getDo ...

What is the reason behind needing to restart the server each time I make a change to my React application?

I'm diving into my first project using React, stepping away from my usual tools of pure HTML, JavaScript, PHP, and Node.js. I decided to create a single-page application portfolio, but I've encountered a frustrating issue. Every time I make a cha ...

Adding as HTML in Angular

I am looking to insert HTML content dynamically in Angular <div class="storycontent" ng-class="{show: show}"> <a href="#/profile?{{review.id}}">{{review.name}}</a>: {{review.story}} </div> Within the {{review.story}}, there ...

Revisiting Async Await: A guide to implementing callbacks

I have the following code snippet: const myImage = document.querySelector('img'); const myRequest = new Request('flowers.jpg'); fetch(myRequest).then((response) => { console.log(response.type); // returns basic by default respo ...

Evaluating the parser for oauth2 implicit grant access_token using javascript

I am currently developing an Angular application that utilizes the implicit grant oauth strategy. In case I do not have a valid access token in my cookies, I am redirected to the web interface of the authentication server where I input my credentials and t ...

Strategies for aligning the initial lines of text vertically within a table cell

I am faced with a unique challenge involving a table where the first cell contains the word "name" and the second cell contains some text. Sometimes, this text may include embedded images. The issue arises when an image appears on the first line of the tex ...

Exploring the combined application of the AND and OR operators in JavaScript programming

{Object.keys(groupByMonthApplicants).map((obj,i) => <div key={obj} style={(i > 0 && (this.state.selectedTabId !== 'rejected' || this.state.selectedTabId !== 'approved')) ? {paddingTop:'15px',background:&a ...

Sending data from a Node.js backend to a React.js frontend using res.send

How can I pass a string from my nodejs backend using res.send? app.post("/user", (req,res) => { console.log(req.body.email); res.send('haha'); }); I need to perform certain operations on the front end based on the value of the string retriev ...

jQuery fails to recognize response

Can anyone figure out why my alert isn't functioning correctly? <script type="text/javascript"> function SubmitForm(method) { var login = document.form.login.value; var password = document.form.password.value; ...