by drinchev · 7y ago · 0 comments
For those who don't know private class fields add the weird "#" character for defining them inside the `class {}` block.
class IncreasingCounter {
#count = 0;
get value() {
console.log('Getting the current value!');
return this.#count;
}
increment() {
this.#count++;
}
}
This looks way worse than having what TypeScript did by introducing `public` / `private` keywords. Is there any body
which votes for es-next features such as this one? I wonder how the "#" private field popped up in Chrome specs.1 : https://developers.google.com/web/updates/2018/12/class-fiel...
2 : https://developers.google.com/web/updates/2018/12/class-fiel...
https://github.com/tc39/proposal-class-fields/issues
There's at least three specifically about the #:
https://github.com/tc39/proposal-class-fields/issues/177
https://github.com/tc39/proposal-class-fields/issues/149
https://github.com/tc39/proposal-class-fields/issues/142
Remember to be constructive or just give a thumbs up to comments you like.
This is not to say that there aren't other viable solutions which would avoid the use of the current proposed syntax, but how do you weigh the advantages of avoiding a subjectively "ugly" syntax against the many other, much more concrete concerns that the TC39 has to evaluate when choosing a proposal? Should "the reflexive reaction of many devs when they first see the feature (without taking any time to try it out) is that the syntax is ugly" just be an automatic veto? If not, how strongly should that concern be weighted? Should an otherwise inferior proposal be accepted instead merely because the syntax is slightly prettier?
Ultimately, I think you need to have a person or group of people in authority who will look at all available options and make an informed decision, even over the objections of the uninformed majority. Right now, the TC39 _is_ that informed authority.
Namely they voted for encapsulation / hard-private [#33] as well as comparing private properties of two classes [2], which as a result makes the only possible syntax the one with the `#`.
Unfortunately this comes at the price that once browsers implement this it will become history ( same as the `with` statements [3] and `labels` with `continue` [4] ). Because of backwards compatibility these will never be removed.
Maybe in 2022 TC39 will decide that "use static-type;" will be a mode, such as strict mode, where you can write statically typed JS ( great idea, btw ), where this proposal will make no sense. Another "use class-inheritance;" mode would also finally end the abuse of prototype inheritance with syntax sugar. In this future the `#` will be just a huge annoyance.
#33 : https://github.com/tc39/proposal-private-fields/issues/33
2 : https://github.com/tc39/proposal-class-fields/blob/master/PR...
3 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
4 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
It also didn't help that library authors are over-represented in the committee relative to the regular users of the language.
Ultimately, I agree that we need to have an authority to make the final decision and it helps if it's informed, but we need to be aware that it's not going to be perfect and it will have blind spots, so perhaps a way for people to veto those decisions should exist.
IMHO "No solution" would be better than "bad solution" in this case.
1 : https://github.com/tc39/proposal-class-fields/issues/100
class Example {
#myVar = 100;
getPrivateMyVar() {
return this.#myVar;
}
getLocalMyVar() {
return this.myVar();
}
}
const example = new Example();
example.myVar = 200;
console.log(example.getPrivateMyVar()) // 100;
console.log(example.getLocalMyVar()) // 200;
I agree the syntax is terrible. But you need to be able to distinguish between the own object property myVar and the private field myVar.example.myVar = 500 should throw an access error.
You don't need to distinguish because you shouldn't be shadowing private variables.
That removes a major benefit of private fields (which is to be able to change implementation details without breaking the public interface)
I don't think anyone really loves the syntax, but there doesn't seem to be much of a better way of doing it.
What are some of the other languages that interpret "private" as never exposing the existence of that field to a public consumer? Most languages I've used don't expose the _value_ of the field...
"Having a private field named x must not prevent there from being a public field named x, so accessing a private field can't just be a normal lookup. This is only an issue in JavaScript because of its lack of static types. Statically typed languages use type declarations to distinguish the external-public/internal-private cases without the need of a sigil. But a dynamically typed language doesn't have enough static information to differentiate those cases." [0]
There are also performance concerns to changing the lookup logic without the sigil. More info in the link.
0: https://github.com/tc39/proposal-class-fields/blob/master/PR...
Sure, you say, that's because in PHP a public property and a private property cannot have the same name. Correct. Why is this a requirement? What problem is this trying to solve? In e.g. older Python we would use the convention of a leading underscore to indicate that a property is private, even if technically one _could_ access it publicly it was understood that is a bad idea to do in practice. It's not a security issue - in every language one could read the "private" properties by some method or another. Reflection, for instance. Or, back to PHP, by casting the object to an array (I did mention that PHP is the canonical hate-it dynamically-typed language).
> Having a private field named x must not prevent there from being a public field named x, so accessing a private field can't just be a normal lookup.
Why do classes support public/private fields of the same name in the first place? This seems fraught by nature?
class A {
#x = 100;
}
const a = new A();
a.x = 200;
On top of this, you should be able to define private variables and methods in derived classes without interfering with the base class private properties: class A {
#x = 100;
getA() { return this.#x }
}
class B extends A {
#x = 200;
getB() { return this.#x }
}
const b = new B();
b.getA() // 100
b.getB() // 200;Intuitively, you would expect the subclass to essentially be saying "my version of this variable is equal to 200, not 100". Then both calls should return the same result (200)
I think the feature is good but couldn't they find a different character than one used for comments almost everywhere else?
But it is an object property, just like everything else attached to "this".
That "this.foo" is not "this.#foo" that's because "foo" is a different key than "#foo".
The current idea is that private fields are kinda like this:
export class Bar {
#foo = 100;
setFoo(value) {
this.#foo = value;
}
getFoo() {
return this.#foo;
}
getFooFromOtherBar(otherBar) {
return otherBar.#foo;
}
}
// similar to (but implemented differently I'm sure)
const barPrivate = new WeakMap(); // properties are only private if this is never exported
export class BarWithoutPrivateFields {
constructor() {
barPrivate.set(this, {});
barPrivate.get(this).foo = 100;
}
setFoo(value) {
barPrivate.get(this).foo = value;
}
getFoo() {
return barPrivate.get(this).foo;
}
getFooFromOtherBar(otherBar) {
return barPrivate.get(otherBar).foo;
}
}
It is NOT a property key!There has been a lot of discussion regarding public and private keywords here: https://github.com/tc39/proposal-class-fields/blob/master/PR...
JavaScript is not static, you don't have a compiler that can protect against access, so you need info that is preserved at runtime.
`#count` in this case is a different name than `count` and via this naming convention it's able to protect access. I don't get the point though, since people already use underscores as a soft mechanism for protecting access to private stuff and in a dynamic language like JS I don't think you need more.
I also think the TC39 proposals are doing more harm then good and they should just stop changing JavaScript. Just leave it the way it is, thanks.
"Promise" for example sucks, in spite of receiving early feedback, because TC39 is run by certain individuals that outright reject feedback that doesn't comply to their world view.
Is there? The object.#foo syntax tells you it is private, sure… but you still need know if access is permitted or not. For that, you need to look at some information on object and make a decision, but that information could also inform you as to whether or not the access is to a private field at all. Consider for object.foo, the following:
1. look up, internally in the interpreter, the class definition (recorded when parsing the class {} block)
2. Is .foo private? If no, behave "normally"
3. If yes, decide if access should be allowed.
What about that doesn't work? If that does work, then, the # is pure syntax.One thing I'm curious about, since you seem adamant that this isn't syntax (particularly since the docs raise the peculiar "SyntaxError" — which implies determining at parse time whether a give obj.#thing is valid): is it only accessible through this.#foo? That is, if I have a class with a member function that takes another instance of the same class, is JavaScript going to tell me that I can't access private fields, despite those being on the current class? (This is fairly different from most languages, and makes some things impossible to express while keeping internals private.)
Why couldn't it? E.g why not let it interfere...
Please roll this back, what a nightmare!
Many system programmers will think this line is commented out. Indeed what a nightmare!
The muscle memory is so strong, when writing Javascript/Typescript I type # by accident sometimes.
But then, // is one of the most commonly used operators in another language I use, so it's weirdly symmetrical :)
That abomination requires as much rationale as they can produce in the given time frame.
Good design doesn't require such degree of mental gymnastics.
Is this problem found anywhere else in the programming world at this scale?
Looks like Typescript conventions say not to do that. Either way the compiler should throw an error if trying to access a private incorrectly.
In JS I guess it helps reduce runtime errors since there is no compiler to check for you and again very clearly visible in code its a private.
Its sort of old school, like Hungarian notation where you would prefix variable with type identifiers except they really mean something.
Language design is hard but is there legitimate criticism besides subjective "I don't like this" ...
I wouldn't be surprised if this here is them giving that dominance a first shot. I'm sure they realize that developers will think it's horrible, but at the same time it's also not a problem. Nothing will break because of this, no company will be disadvantaged by it (barring Mozilla ofc). Perfect opportunity for testing the waters of a newly obtained monopoly position.