Hacker News new | ask | show | jobs
by nobleach 909 days ago
I'm not a fan of it there either. JavaScript, since its earliest days, had `private` as a reserved word. Typescript makes use of it. It conveys perfectly what the Class member's visibility should be. Using `#` might be easier on parsers, or may fix some sort of compatibility issue (I haven't read the reasoning) but it's silly.
1 comments

There's a lot of reasoning for it, mostly summarized by "this.abc and this.#abc are not the same fields".

The goal of #-private properties in JS is to have total runtime isolation, so that there's no way at all to access it from the outside. If you're fine with a compile-time error, use TypeScript's private keyword instead (JS does not have a compiler).

But why can't `otherObj.abc = 3` throw an error if abc is declared as private? Because it would incur a runtime cost on all property accesses to check whether it's public or not, even if private properties aren't used anywhere within the class. Not a sacrifice anyone would be willing to make.

So, the solution is to make sure that private property accesses can be distinguished from public property accesses. You could have had something like `private.abc` instead of `this.#abc`. But I don't think that's better, either.

Honestly, you'll get used to # if you use it for a while.

This is similar to the recent post about private members in Ruby. It's a sytaxical check that the receiver is literally 'this'. Which, like you say, can be checked at parse time without any lookups. Even identity(this).privateVar doesn't pass in Ruby due to not being sytaxical this.