我想从派生类访问基类的私有(private)字段而不将其公开(在其他语言中称为“ protected ”)。
考虑下面的类:
class Animal {
#privateProp;
constructor() {
this.#privateProp = 12;
}
}
现在是扩展类:
class Cat extends Animal {
constructor() {
super();
}
doIt() {
console.log(this.#privateProp) // 1 below
console.log(super.#privateProp) // 2 below
}
}
我想像 protected 一样执行:
new Cat().doIt();
但得到(分别):
- Uncaught SyntaxError: Private field '#privateProp' must be declared in an enclosing class
- Uncaught SyntaxError: Unexpected private field
请注意,当 privateProp 变为公共(public)时,此代码将完美运行,但我想实现类似 protected 行为,并像任何支持继承的语言一样访问“私有(private)”字段。
任何帮助将不胜感激。
最佳答案
you can create a private property with getter and setter methods having restricted access by checking if the constructor is not of the parent class itself.
class Animal {
#privateProp = 12;
set Prop(val) {
if (this.constructor.name !== 'Animal')
return this.#privateProp = val;
throw new Error('Cannot Access Protected property');
}
get Prop() {
if (this.constructor.name !== 'Animal')
return this.#privateProp;
throw new Error('Cannot Access Protected property');
}
}
class Cat extends Animal {
get Prop() {
return super.Prop;
}
set Prop(val) {
super.Prop = val
}
}
let cat = new Cat();
console.log(cat.Prop)
cat.Prop = 22
console.log(cat.Prop)
console.log(new Animal().Prop);
关于javascript - 从派生类访问基类的 protected 字段(ES2019 私有(private)类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61225283/