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?
In a JavaScript class, to declare something as “private,” which can be a method, property, or getter and setter, you have to prefix its name with the hash character “#”.
Short answer, no, there is no native support for private properties with ES6 classes. But you could mimic that behaviour by not attaching the new properties to the object, but keeping them inside a class constructor, and use getters and setters to reach the hidden properties.
There are two major disadvantages of creating the true private method in JavaScript. Cannot call private method outside the class. Create memory inefficiency when different objects are created for the same class, as a new copy of the method would be created for each instance.
Use closure() to Create Private Properties in JavaScript Using closure() is one of the choices to implement private properties in JavaScript. Inner functions with access to the variables of the surrounding function are known as closures. You can access this link to see the working of this code.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With