Skip to main content

Private fields, public worries

Filip Białek

Nov 7, 2019|7 min read
Image Alt
Image Alt

1class BankAccount {
2 balance = 0;
3 #clientId = ‘xyz’;
4 deposit = (amount) => {
5 this.balance += amount;
6 };
7 getId = () => this.#clientId;
8}
1class Widget extends React.Component {
2 state = {
3 open: false
4 };
5 toggle = () => {
6 this.setState(prevState => ({
7 open: !prevState.open
8 })
9 };
10 render...
11}

It means that private fields are purely internal: no JS code outside of a class, can detect or affect the existence, name, or value of any private field of instances of said class without directly inspecting the class’s source unless the class chooses to reveal them.

Most people said please stop the proposal, we can’t stand the sigil

No one came out and said, # is the most beautiful, intuitive thing to indicate private state. Instead, it was more of a process of elimination

1class Widget {
2 private mySecret = '1234';
3}
4const obj = new Widget();
5obj.mySecret = '5689';

Either it’s fully “hard private” — inaccessible and unobservable — or else it’s fully public.

Subscribe to our newsletter and never miss an article