如何在纯 ES6 class 中编写 public 字段

How to write public fields in pure ES6 class

在 ES6 class 中可以有 public 字段,像这样:

class Device {

    public id=null;
    public name=null;

    constructor(id,name,token) {
        this.id = id;       // I want this field to be public
        this.name = id;     // I want this field to be public

        this.token = token; // this will be private
    }
}

我知道拥有私有字段很容易——只需将它们放在构造函数中(如上面示例代码中的 'token' 字段)——但是 public 字段呢?

实际上,如果您在构造函数中将某些内容分配给 this 的 属性,该字段将为 public。 ES6 类.

中没有私有字段

class Test {
  constructor(name) {
    this.name = name;
  }
}

const test = new Test("Kamil");
console.log(test.name); // "Kamil"