Note: I already went through the below SO Question and 7 Answers (as of now) about Symbols, WeekMaps and Maps, Please read the full question before you vote: Private properties in JavaScript ES6 classes
Article: https://esdiscuss.org/topic/es7-property-initializers
Below is my Simple Class
which contains Private, Public and Protected Properties and Methods.
'use strict';
class MyClass {
constructor () {
this.publicVar = 'This is Public Variable';
this.privateVar = 'This is Private Variable';
this.protectedVar = 'This is Protected Variable';
} // Public Constructor Method.
publicMethod () {
console.log(' Accessing this.publicVar: ', this.publicVar);
console.log(' Accessing this.privateVar: ', this.privateVar);
console.log(' Accessing this.protectedVar: ', this.protectedVar);
return 'Its Public Method'
} // Public Method.
privateMethod () {return 'Its Private Method'} // Private Method.
protectedMethod () {return 'Its Protected Method'} // Protected Method.
foo () {
this.publicMethod();
this.privateMethod();
this.protectedMethod();
} // Public Method
} // end class
I'm instantiating the Object and calling the public method which is working as expected.
let MyObject = new MyClass;
MyObject.foo(); // Works fine.
console.log( MyObject.publicVar ); // Works
console.log( MyObject.publicMethod() ); // Works
Working as expected.
Now my question. I'm aware few things like Symbol are in the ES6 specification, what is the current workaround to get protected and private variables/methods working on ES6 classes.
console.log( MyObject.privateVar ); // Works
console.log( MyObject.privateMethod() ); // Works
I want this property and method to be visible only in its own class.
console.log( MyObject.protectedVar ); // Works
console.log( MyObject.protectedMethod() ); // Works
I want this property and method to be visible in its own class and inside classes extending it.
Workaround / better solution to achieve this behavior is appreciated