JavaScript ES6 Private Fields and Methods
How to create private fields and methods within JavaScript ES6 classes.
Introduction
Below is an example I created, demonstrating how to create private
fields and methods within JavaScript ES6 classes.
Example Code
I was able to achieve private
fields and methods by doubling class with class.
// Private Class Definition
class test
{
// Private Method
get(){ console.log('Private Get Hello'); }
// Private class constructor
constructor()
{
// Private Fields
this.fields = [];
// Private Instance
const self = this;
// Public Class Definition
class test
{
// Public Properties to Private Fields
set counter(_counter) { self.fields['counter'] = _counter; }
get counter() { return self.fields['counter']; }
// Public Constructor
constructor()
{
console.log(arguments);
}
// Public Method
increase()
{
self.fields['counter'] += 1;
console.log(self.fields);
}
// Public Method to Private method
get()
{
self.get();
}
}
return new test(...arguments);
}
}
var a = new test(54321,'abc');
console.log(a);
a.counter = 1234;
a.increase();
a.get();
console.log(a.fields); // <-- Undefined Private