How to implement private method in ES6 class with Traceur [duplicate] How to implement private method in ES6 class with Traceur [duplicate] javascript javascript

How to implement private method in ES6 class with Traceur [duplicate]


There are no private, public or protected keywords in current ECMAScript 6 specification.

So Traceur does not support private and public. 6to5 (currently it's called "Babel") realizes this proposal for experimental purpose (see also this discussion). But it's just proposal, after all.

So for now you can just simulate private properties through WeakMap (see here). Another alternative is Symbol - but it doesn't provide actual privacy as the property can be easily accessed through Object.getOwnPropertySymbols.

IMHO the best solution at this time - just use pseudo privacy. If you frequently use apply or call with your method, then this method is very object specific. So it's worth to declare it in your class just with underscore prefix:

class Animal {    _sayHi() {        // do stuff    }}


You can always use normal functions:

function myPrivateFunction() {  console.log("My property: " + this.prop);}class MyClass() {  constructor() {    this.prop = "myProp";    myPrivateFunction.bind(this)();  }}new MyClass(); // 'My property: myProp'


Although currently there is no way to declare a method or property as private, ES6 modules are not in the global namespace. Therefore, anything that you declare in your module and do not export will not be available to any other part of your program, but will still be available to your module during run time. Thus, you have private properties and methods :)

Here is an example(in test.js file)

function tryMe1(a) {  console.log(a + 2);}var tryMe2 = 1234;class myModule {  tryMe3(a) {    console.log(a + 100);  }  getTryMe1(a) {    tryMe1(a);  }  getTryMe2() {    return tryMe2;  }}// Exports just myModule class. Not anything outside of it.export default myModule; 

In another file

import MyModule from './test';let bar = new MyModule();tryMe1(1); // ReferenceError: tryMe1 is not definedtryMe2; // ReferenceError: tryMe2 is not definedbar.tryMe1(1); // TypeError: bar.tryMe1 is not a functionbar.tryMe2; // undefinedbar.tryMe3(1); // 101bar.getTryMe1(1); // 3bar.getTryMe2(); // 1234