gpt4 book ai didi

javascript - 从派生(ES2019 私有(private)类)访问基类的 protected 字段

转载 作者:行者123 更新时间:2023-12-04 10:13:07 25 4
gpt4 key购买 nike

我想从派生类访问基类的私有(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
}
}

我想像受到保护一样执行:
new Cat().doIt();

但是得到(分别):

  1. Uncaught SyntaxError: Private field '#privateProp' must be declared in an enclosing class
  2. Uncaught SyntaxError: Unexpected private field


请注意,当 privateProp 公开时,此代码将完美运行,但我想实现类似 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 - 从派生(ES2019 私有(private)类)访问基类的 protected 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61225283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com