6

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 privateFunction = function () {
    return 0;
  };

  this.publicFunction = function () {
    return 1;
  };
}

as

class MyClass {

  // ???

  publicFunction () {
    return 1;
  }
}
JS.Ziggle
  • 81
  • 5

1 Answers1

4

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

class MyClass {
  constructor() {
    var privateFunction = function () {
      return 0;
    };

    this.publicFunction = function () {
      return 1;
    };
  }
}

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    In theory, true privacy will be in ES7. – T.J. Crowder May 19 '15 at 14:52
  • True privacy via syntax perhaps., but you can already get true privacy via WeakMaps. – loganfsmyth Jul 07 '15 at 15:38
  • This way, you're defining a `publicFunction` in every instance of your `MyClass` members, instead of defining it once on `MyClass.prototype` – Masious Nov 21 '18 at 11:37
  • @Masious: yes, that’s necessary if `publicFunction` needs to access `privateFunction`. That’s why I said if it doesn’t need to access `privateFunction` it could be a “real method”. But I could have expressed that clearer. – Felix Kling Nov 21 '18 at 15:55