How to implement private method in ES6 class with Traceur
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'
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
}
}