Private Members

A private memberprivate member private member is a property or method which can only be accessed by methods within the class. As of July 2017, there is no native support for private properties and methods. Symbols can be used to provide 'an extra level of privacy', by preventing the keys/properties of an object from being exposed through some popular methods such as for...in, Object.keys() and JSON.stringify().


RESETRUNFULL
<!DOCTYPE html><html><body><script>

let Person = (function(){
   let age = Symbol();                               // declared in another module perhaps?
   class Person {
      constructor(n,a){
         this.name = n;
         this[age] = a;
        }
      introduce(){
         console.log(
         `My name is ${this.name}. I am ${this[age]-10}.`);
      }
   }
   return Person;})();var j = new Person('Jane',45);j.introduce();  // My name is Jane. I am 35.console.log(JSON.stringify(j)); // {"name":"Jane"}console.log(Object.keys(j)); // ["name"]console.log(j[Object.getOwnPropertySymbols(j)[0]]);  // 45

</script></body><html>

Although given an object per se, such properties can still be exposed through Proxy (8.21), Object.getOwnPropertySymbols(), etc., there is no natural means to access them through a few direct methods, which may be sufficient sometimes from an OOP perspective.A more effective alternative is to use a scoped WeakMap (8.15), which is not enumerable at all.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

let Person = (function () {
   let privateProps = new WeakMap();
   class Person {
      constructor(name) {
         this.name = name; // this is public
         privateProps.set(this, {age: 45}); // this is private
       }
       greet() {  // Here we can access both name and age
          console.log(`I am ${this.name}.
                           I am ${privateProps.get(this).age-10}.`);
       }
   }
   return Person;})();let j = new Person('Jane');j.greet();console.log(j.privateProps);  // undefined

</script></body><html>

Private fields using the # syntax are an experimental technology at the time of writing.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

class C1{
    v1 = 1;    // public, accessible everywhere
    #v2;        // private, accessible only within this class
    constructor(value){
        this.#v2 = value;
    }}class C2 extends C1{
    constructor(){
        super();        //this.v3 = this.#v2;   // error
    }}const o = new C2;console.log(o.v1);  // 1//console.log(o.#v2);/* Uncaught SyntaxError: Private field '#v2' must be declared in an enclosing class */

</script></body><html>