3 ms·
It'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
by __ryan__ 8y ago
It'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 _.