Open mgaudet opened 4 years ago
Private fields and methods are designed to have higher integrity by default, leading to exceptions rather than silent failures, in a number of cases:
In all cases, the goal is to make it easier to understand the usages of private fields, locally analyze what some code will do, avoid unintentional effects which could lead to kinds of leaks, and catch errors from misuse.
We should improve documentation around this motivation, so I'm leaving this issue open and adding the documentation label.
(I'm confused by the code sample in your question; it's a syntax error, and doesn't use private fields.)
The formatting was funky; it's an abbreviated minimal example. I tweaked the formatting to be a little clearer what was going on (but works for me?) The point was to highlight the refactoring barrier, but that's exactly your point 3, so it's a known design point.
The design principle of having higher integrity by default makes sense; Given my impression this has been discussed at length elsewhere, leaving this as a doc issue makes sense to me.
In the code, the block containing a = 1 is outside the class body; i think you have a misplaced closing curly brace.
No: I'm extending an anonymous class which has a constructor.
Edit: I did not realize that would be confusing, so here's the same thing rewritten with two classes for clarity:
class Base { constructor(o) { return o; } };
class Derived extends Base
{
a = 1;
};
var obj = {};
new Derived(obj);
new Derived(obj);
Thanks, you’re totally right and that clears it up :-)
So private fields has a little quirk compared to public fields, and I'm trying to understand why the restriction exists.
The quirk:
This is fine, with a public field. But if you change that to a private field, by going
a => #a
, then the second constructor call is supposed to issue a type error: PrivateFieldAdd, step 4.What I don't really understand is why this change in semantics relative to public fields? It feels weird to have these two parallel constructs that don't behave the same in parallel situations.
(There's also an albeit very small argument that this also makes refactoring public fields into private fields more of a footgun, as code which would work on public fields breaks when translated into a private field for reasons outside of visibility)