Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 classes private member syntax [duplicate]

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;
  }
}
like image 592
JS.Ziggle Avatar asked May 12 '15 12:05

JS.Ziggle


1 Answers

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.

like image 187
Felix Kling Avatar answered Oct 04 '22 20:10

Felix Kling