javascriptclassecmascript-5ecmascript-6traceur

How to implement private method in ES6 class with Traceur


I use Traceur Compiler to have advantage with ES6 features now.

I want to implement this stuff from ES5:

function Animal() {
    var self = this,
        sayHi;

    sayHi  = function() {
        self.hi();
    };

    this.hi = function() {/* ... */}
}

Currently traceur does not support private and public keywords (from harmony). And ES6 class syntax does not allow to use simple var (or let) statements in class body.

The only way that I am find is to simulate privates before class declaration. Something like:

var sayHi = function() {
    // ... do stuff
};

class Animal {
...

It is better then nothing but as expected you can not pass correct this to private method without apply-ing or bind-ing it every time.

So, is there any possibility to use private data in ES6 class compatible with traceur compiler?


Solution

  • 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
        }
    }