Skip to content

Instantly share code, notes, and snippets.

@EmielZuurbier
Last active January 14, 2020 01:37
Show Gist options
  • Save EmielZuurbier/af48330a3a17dade5646d8ae6da6695e to your computer and use it in GitHub Desktop.
Save EmielZuurbier/af48330a3a17dade5646d8ae6da6695e to your computer and use it in GitHub Desktop.
Private instance field of JavaScript of a class example.
/**
* Not precisely a "read-only" property but it can (in the near future) behave as one with
* ES2019 spec private instance fields. With a single get method and a "private instance field"
* it is possible to simulate the effect, like the examples above, with the added bonus of having
* the private property truly hidden.
*
* Although MDN is not the ultimate authority, their examples don't show the necessity to have a `setter`
* with a `getter`. Making having only a `getter` already a case of having a "read-only" value.
*
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields
*/
class Counter {
#count = 0;
increment() {
this.#count++;
}
decrement() {
this.#count--;
}
get currentCount() {
return this.#count;
}
}
const counter = new Counter();
counter.increment();
counter.increment();
counter.decrement();
counter.currentCount; // 1
counter.currentCount = 3; // 3
counter.currentCount = 'everything'; // 'everything'
counter.currentCount; // 1
counter.count; // undefined;
counter.#count // Uncaught SyntaxError: Private field '#count' must be declared in an enclosing class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment