How do we get access to a private variable in ES6 class?

Below we define a private variable boy for a would-be instance of the class ‘Forrest’. By doing this JavaScript signals of no mistakes. But neither the instance, nor Forrest.prototype or Forrest constructor function itself show no signs of hosting this variable.

class Forrest {
  constructor() {
    let boy = "Bobby";
    girl: "Marry";
  }
}

const f = new Forrest();

However we can easily get access to this private boy variable via vanilla constructor function.

function Forrest() { 
  let boy = "Bobby"; 
  return function() { 
    console.log(boy);
  } 
} 

const f = new Forrest();
f(); // Bobby 

How do we get access to this private variable in ES6 class?

27 thoughts on “How do we get access to a private variable in ES6 class?”

  1. let boy is a variable only valid within the constructor’s scope

    girl: "Marry" is not a property at all

    This is how you initialize and access attributes

    class Forrest {
      constructor() {
        this.boy = "Bobby"
        this.girl = "Marry"
      }
    }
    
    const f = new Forrest();
    console.log(f.boy)
    console.log(f.girl)
    Reply

Leave a Comment