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?
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.
Comments