So far, private fields are introduced as follows:
class MyClass {
#privateField = 123;
}
I’d like to propose a small extension: scoped private fields.
The following style is becoming popular in the JavaScript world. It benefits from scoped privacy:
private #data;
function createStringBuilder() {
return {
#data: '',
};
}
function add(sb, str) {
sb.#data += str;
}
function toString(sb) {
return sb.#data;
}
New in this code:
- The keyword
private
in the first line. - The ability to use private fields in object literals.
As a slight downside, you now always need to use the keyword private
:
class StringBuilder {
private #data = ''; // keyword is required
add(str) {
this.#data += str;
}
toString() {
return this.#data;
}
}
On the upside, this gives you the freedom to widen the scope of privacy:
private #data;
class StringBuilder {
#data = ''; // no keyword!
add(str) {
this.#data += str;
}
}
function toString(stringBuilder) {
return stringBuilder.#data;
}
Alternative syntax has been proposed:
- Keyword
private
not needed for “normal” private fields. - Two keywords if you want to widen the scope of privacy:
private
andouter
.
Example:
private #data;
class StringBuilder {
outer #data = ''; // keyword is now required
add(str) {
this.#data += str;
}
}
function toString(stringBuilder) {
return stringBuilder.#data;
}
FP example:
private #data;
function createStringBuilder() {
return {
outer #data: '', // keyword is now required
};
}
function add(sb, str) {
sb.#data += str;
}
function toString(sb) {
return sb.#data;
}
Good writeup, Axel.
To be clear, this gist is proposing a change in the Stage 3 proposal https://github.com/tc39/proposal-class-fields , to require the
private
keyword in private field and method declarations where it was previously implicit, implied by the#
. Although it should be easier on a first read to haveprivate
be explicit, I was thinking to leave that keyword out to avoid repetition (once you learn what#
means, it may be annoying to keep repeatingprivate
). The private declaration proposal might make this extra verbosity "pay for itself".For a contrast, I've suggested that we use a different syntax for this purpose in https://github.com/tc39/proposal-static-class-features/blob/master/FOLLOWONS.md#private-names-declared-outside-of-classes , which would not require adding the
private
keyword in the common case of a class declaration.