Proposal: keyword to replace #
sigil · Issue #56 · tc39/proposal-class-fields (original) (raw)
This repository was archived by the owner on Jan 25, 2022. It is now read-only.
This repository was archived by the owner on Jan 25, 2022. It is now read-only.
Description
(I have edited this description from the original in response to feedback; original is here)
In https://github.com/tc39/proposal-private-fields, I see a redirect to this repo for future discussion and current status, as well as this:
Q: Can we reconsider, in the syntax, the decision to do...
A: Yes, it's not too late.
There seems to be general dissatisfaction with the #
sigil for private fields. I would like to propose an alternate syntax with the same semantics:
Use a private
unary prefix keyword to access a "private this", such that private this.foo
is identical to the currently proposed #foo
.
class Point {
private x;
private y;
constructor(x = 0, y = 0) {
private this.x = +x;
private this.y = +y;
}
get x() { return private this.x }
set x(value) { private this.x = +value }
get y() { return private this.y }
set y(value) { private this.y = +value }
equals(p) { return private this.x === private p.x && y === private p.y }
toString() { return `Point<${ private this.x },${ private this.y }>` }
}
Other possibilities for the keyword include:
Advantages:
private
is already reserved, and would have no other reasonable use.#
is the only "free sigil" left on a US keyboard for JavaScript (that I know of) and might be better saved for a feature which would be used in both application and library code, rather than only library code.- It is immediately clear what
private.
is for;#
is not likely to be immediately clear. - It would be friendlier to existing language tooling and implementations (eg; syntax highlighters, static analysis tools, and parsers would require minimal/no modification).
It is more obvious thatprivate this.x
andthis.x
are completely separate, and can peacefully coexist as unrelated fields.- It resolves the surprising difference between
this.#x
andthis['#x']
.
Downsides:
private this.foo
would likely be surprising to a Java or C# engineer, whereprivate
is used differently. (I would argue this is similar to the existingself
/this
differences).private
is already implemented in TypeScript, and this would clash. (I would argue TypeScript would likely be able to adapt).
(original proposal was private.foo
instead of private this.foo
)