I'd like to access private fields of base class from derived classes without making them public (what is called 'protected' in other languages).
Consider the following class:
class Animal {
#privateProp;
constructor() {
this.#privateProp = 12;
}
}
Now the extending class:
class Cat extends Animal {
constructor() {
super();
}
doIt() {
console.log(this.#privateProp) // 1 below
console.log(super.#privateProp) // 2 below
}
}
I'd like to execute as if it was protected:
new Cat().doIt();
But gets (respectively):
- Uncaught SyntaxError: Private field '#privateProp' must be declared in an enclosing class
- Uncaught SyntaxError: Unexpected private field
Notice that this code would work perfectly when privateProp becomes public, But I want to achieve a protected like behavior and get access to the 'private' fields like any language that support inheritance.
Any help will be appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…