从派生类(ES2019 私有类)访问基类的受保护字段 [英] Accessing protected fields of base class from derived (ES2019 private class)
问题描述
我想从派生类访问基类的私有字段,而不是将它们公开(在其他语言中称为受保护").
考虑以下类:
class Animal {#privateProp;构造函数(){this.#privateProp = 12;}}
现在是扩展类:
class Cat extends Animal {构造函数(){极好的();}做它(){console.log(this.#privateProp)//1 下面console.log(super.#privateProp)//2 下面}}
我想像受保护一样执行:
new Cat().doIt();
但是得到(分别):
<块引用>- 未捕获的语法错误:必须在封闭类中声明私有字段#privateProp"
- 未捕获的语法错误:意外的私有字段
请注意,当 privateProp 变为 public 时,此代码将完美运行,但我想实现类似受保护的行为,并像任何支持继承的语言一样访问私有"字段.
任何帮助将不胜感激.
您可以使用 getter 和 setter 方法创建私有属性通过检查构造函数是否不属于父类本身.
class Animal {#privateProp = 12;设置 Prop(val) {if (this.constructor.name !== 'Animal')返回 this.#privateProp = val;throw new Error('无法访问受保护的属性');}获取道具(){if (this.constructor.name !== 'Animal')返回这个.#privateProp;throw new Error('无法访问受保护的属性');}}类猫扩展动物{获取道具(){返回 super.Prop;}设置 Prop(val) {super.Prop = val}}让 cat = new Cat();console.log(cat.Prop)cat.Prop = 22console.log(cat.Prop)console.log(new Animal().Prop);
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.
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);
这篇关于从派生类(ES2019 私有类)访问基类的受保护字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!