简体   繁体   English

无法在 javascript 中的 Class 的 object 中声明对象

[英]cannot declare objects inside an object of a Class in javascript

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?为什么我们不能在 class 中执行此操作(在 class 中创建一个 object 并为其赋予属性)?

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.另一方面,没有什么能阻止您使用更详细的 object 文字来初始化该字段。

NB: to create an instance you should use the new keyword.注意:要创建实例,您应该使用new关键字。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM