I'm just trying out ES6 and want to rewrite a part of code written in regular javascript to ES6. And now, I'm stuck while trying to re-write the private properties and methods in ES6 classes. It seems like classes in ES6 doesn't explicitly provide anything to have private data or methods.
Also, I checked this thread: Private properties in JavaScript ES6 classes and found out that we could use WeakMap to store private data. Which is sort of weird but still it can be a work around. And I did manage to use it for private data.
But what about private methods? What is the recommended way to have private methods (or even protected methods) in ES6 classes?
I would appreciate if anyone can show me a clean way to rewrite this part of code using ES6 class along with the private methods.
Thanks.
Here's the plain old javascript code:
function Deferred() {
// Private data
var isPending;
var handlers = {
resolve: [],
reject: [],
notify: []
};
// Initialize the instance
init();
function init() {
isPending = true;
this.promise = new Promise(this);
}
// Public methods
this.resolve = function(value) {
trigger('resolve', value);
};
this.reject = function(reason) {
trigger('reject', reason);
};
this.notify = function(value) {
trigger('notify', value);
};
this.on = function(event, handler) {
...
};
// Private method
function trigger (event, params) {
...
}
}