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;
}
The
private
keyword feels more natural, especially when coming from other languages such as TypeScript, Java, C#, etc.I don't see the point of keeping the
#
character if theprivate
keyword is used though; when both are used one of them is redundant.The
private
keyword could essentially be syntax sugar for the#
character.