cannot declare objects inside an object of a Class in javascript

Vitor_figm
class A{
    obj = {};
    obj.x = 0;
}

let a = new A()

Why we cannot do this(create an object inside a class and give it a property) inside a class?

trincot

You can define instance fields with that syntax (outside of the constructor), but not mutate them. Don't confuse the = syntax with the usual assignment syntax, as it really has different rules. For instance you can also use this syntax:

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

If you want to mutate fields/properties, you'll have to do this inside the constructor or other method. On the other hand, nothing stops you to initialise the field with a more elaborate object literal.

NB: to create an instance you should use the new keyword.

So either do:

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

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

Or do:

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Declare an object inside or outside a loop?

Cannot declare Public static final String s = new String("123") inside an inner class

how can does one declare a sub-class object inside of a base class without leading to recursion errors?

Typescript: declare empty class object

NSKeyedUnarchiver decodeObjectForKey: cannot decode object of class for key (NS.objects)

Declare size of a vector inside class

Function inside an object cannot access that object in javascript

Declare method inside class dynamically

Cannot accsess array of objects inside same class?

Can I in Scala declare the class inside its companion object?

Typescript definitions: how to declare class inside class

how to declare and make objects inside another object's constructor?

How to declare an ArrayList of objects inside a class in java?

Declare a public "static" function inside a JavaScript class

Vector/Array inside Object, Holding Objects of Another Class

Fatal error: Cannot declare class

Declare an object as a specific class in php

Javascript global object cannot be accessed inside function

Javascript: Add margin-top to an object, object with other objects is inside object A, multiple objects A on page

how to declare an object in javascript es6 class constructor

Declare object type in class

How to declare a class object in Kotlin

How access class/Object inside function in javascript?

Javascript Create Object inside Objects dynamically

Declare an object as abstract class

Declare a structure which is inside a class

How to access object atribute inside a list of objects that is an atribute of a class in python?

Should we declare methods inside or outside the constructor in a class definition in JavaScript?

How to declare a <vector> object and use push_back inside a class?