In a class
, how do I access its base-class's private field, say #property
?
class Base {
#property = '1.618'
toString() {
return Base.name
}
}
class X extends Base {
thisWorks() {
return super.toString()
}
toString() {
return super.#property // SyntaxError: Unexpected private field
}
}
console.log(`${new X}`)
It is impossible:
It means that private fields are purely internal: no JS code outside of a class can detect or affect the existence, name, or value of any private field of instances of said class without directly inspecting the class's source, unless the class chooses to reveal them. (This includes subclasses and superclasses.)
Base
would have to deliberately expose its #property
in some other way, like through a method.