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;
}
@rauschma's comment and the FAQ on the proposal make it clear as day to be honest - it makes sense for the language. Yes, it looks ugly at first and not like standard JavaScript style declaration (which uses keywords for everything else), but I think we'll get used to it. On the other hand, I was wondering if during compile time,
private field
can be mapped over to#field
? I guess that means during access you'll have to remember to use the #, but during declaration it would look different. Not sure if that would be better or not actually, but it seems like a good middle ground?~ thankful for everything OSS contributors do, and the TC39 committee as well!