scoped-private.md (original) (raw)
Sketch: scoped private fields
So far, private fields are introduced as follows:
class MyClass { #privateField = 123; }
I’d like to propose a small extension: scoped private fields.
Functional style (the proposal)
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.
OOP style
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
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; }