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
privatein 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
privatenot needed for “normal” private fields. - Two keywords if you want to widen the scope of privacy:
privateandouter.
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;
}
#is blatantly awful, non-intuitive and will only fuel theJavaScript is a flawed languageadage (which I have to agree to if this#symbol is introduced).privateshould be the way to declare private fields. The fact we're having a year-long discussion about this thing is what sometimes makes me question the reliability of the process (and people) upgrading JavaScript. Please, useprivate.