Skip to content Skip to sidebar Skip to footer

Es6 Classes Private Member Syntax

I have a quick question. What's the cleanest and straightforward way to declare private members inside ES6 classes? In other words, how to implement function MyClass () { var pr

Solution 1:

It's not much different for classes. The body of the constructor function simply becomes the body of constructor:

classMyClass {
  constructor() {
    var privateFunction = function () {
      return0;
    };

    this.publicFunction = function () {
      return1;
    };
  }
}

Of course publicFunction could also be a real method like in your example, if it doesn't need access to privateFunction.

I'm not particularily advising to do this (I'm against pseudo privat properties for various reasons), but that would be the most straightforward translation of your code.

Post a Comment for "Es6 Classes Private Member Syntax"