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
function object 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 JS constructor function.
function Forrest() {
let boy = "Bobby";
this.getBoy = function() {
console.log(boy);
}
}
const f = new Forrest();
f.getBoy(); // Bobby
How do we get access to this private (local) variable in ES6 class?