4 ms·
From the syntax proposal: > 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
by throwaway427 8y ago
From the syntax proposal:
> 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?
- __ryan__ 8y agoIt's more of a side effect that the class can define these properties of the same name. The real goal is that in the following example, the private property #x is not affected. 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;
- syspec 8y agoThis example seems like something you shouldn't be able to do. Now you have 2 private '#x' properties with unique values. It's very surprising. 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)
- throwaway427 8y agoAnother comment in this thread noted this is how Java works. I very much agree with you, but I guess there are different interpretations of how this should behave.
- __ryan__ 8y agoThe spec (and the committee) has defined "private fields" to mean that anything outside of the defining class (including subclasses) should have no knowledge of them. If your subclass needs to know about the property, make it "soft private" by prefixing it with _.
- girvo 8y agoI’m guessing the answer is to do with the fact we’re dealing with a prototype chain rather than “regular” classes, and the historical fact that everything is basically public anyway