Private members in JavaScript using Classes

JavaScript isn't designed to have private members. It isn't part of the language in the sense of it being built into a class as the class is just syntactic sugar to prototypal inheritance. This isn't a bad thing, just something to note.

If you use a class factory, you can easily make private members within a closure.

Here's a simple example.

function testClassFactory(constructorArgs) {  
  var privateThing = 'privateThing';
  class Test {
    modifyPrivate(str) {
      privateThing = str + privateThing;
    getPrivate() {
      return privateThing;
  return new Test(constructorArgs);

var test = testClassFactory();  
test.modifyPrivate('testing a ')

var anotherTest = testClassFactory();  
anotherTest.modifyPrivate('testing another');



You could always overcomplicate things with Symbols or unique hash IDs per instance but this actually works and is private because the language does support closures so it isn't unnatural or reaching in that sense.

The downside to this approach is you cannot extend the class declaring it in this manner but if that isn't a requirement then this will work fine for you.