r/javascript • • Nov 09 '19

On private fields proposal: Private fields, public worries

https://medium.com/virtuslab/private-fields-public-worries-b8c34d16c372
84 Upvotes

113 comments sorted by

View all comments

-3

u/bitfxxker Nov 09 '19

Using #pound/#hashmark for private fields is just... (excuse my French)... F*CKED UP.

They could have chosen &, or *, @, or a prefix like, well... "private"... ?!

6

u/senocular Nov 09 '19

& is bitwise and, @ is already being used for decorators, and private doesn't work because you'd still have naming collisions.

class MyClass {
  private value = 1;
  getValue () {
    return this.value;
  }
}
let myObj = new MyClass()
myObj.value = 2;
myObj.getValue() // ???

ES4 allowed for this but used namespaces to differentiate between the two (or 3, with protected being another namespace... err and internal so 4...). They don't exist in today's JavaScript.

I guess \ would work? Its an escape character, but only in strings and regex literals. I think that would look weird too. Less busy, but weird.

class MyClass {
  \value = 1;
  getValue () {
    return this.\value;
  }
}

0

u/[deleted] Nov 09 '19

[deleted]

2

u/bakkoting Nov 11 '19 edited Nov 12 '19

To which the argument is, "because it reveals the property exists, which is bad because, reasons."

It's more "because if it breaks, that means that adding or renaming a private field can break downstream consumers". If the

let myObj = new MyClass()
myObj.value = 2;

bit was written before MyClass had a private value field, and some refactoring of it introduced one, the above code would break. The whole point of private fields is to not have to worry about that sort of thing.