-1

Is possible to have public field in an ES6 class like this:

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
    }
}

I know that is easy to have private field—just by put them in constructor (like 'token' field in example code above)—but what about public fields?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 1
    Possible duplicate of [ES6 class variable alternatives](http://stackoverflow.com/questions/22528967/es6-class-variable-alternatives) – Dekel Jan 29 '17 at 16:39
  • 1
    What do you mean by "public fields"? Regular instance variables are already publicly accessible properties - always have been (same in ES3 to ES6). So your `id` and `name` properties are already accessible by anyone who has your object iinstance. Your question, as it stands now, is unclear what you are asking for. – jfriend00 Jan 29 '17 at 16:40
  • my mistake - I don't check that fields declared in constructor are actually public - and the problem is with private fields – Kamil Kiełczewski Jan 29 '17 at 17:17

1 Answers1

4

Actually, if you assign something to a property of this inside a constructor, the field will be public. There are no private fields in ES6 classes.

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

const test = new Test("Kamil");
console.log(test.name); // "Kamil"
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177