I haven't heard people claim that boy
in your example isn't private. Quite the opposite, it's private to the constructor and getBoy
. Nothing else (including nothing else in that class) can access it. But either way, I suppose that might be in the "opinion-based" realm.
Stepping out of that realm: Regardless of someone may feel about the closure approach shown in the question, JavaScript will have true private fields very, very soon. It's implemented in most major engines and likely to hit the spec this year. Your example with private fields looks like this:
class Forrest {
#boy = "Bobby";
getBoy() {
console.log(this.#boy);
}
}
const f = new Forrest();
f.getBoy() // Bobby
Or if we set it from a constructor parameter:
class Forrest {
#boy;
constructor(boy) {
this.#boy = boy;
}
getBoy() {
console.log(this.#boy);
}
}
const f = new Forrest("Bobby");
f.getBoy() // Bobby
Those will run on up-to-date versions of Chromium-based browsers. Safari and Firefox won't be much longer.