[英]Accessing protected fields of base class from derived (ES2019 private class)
我想從派生類訪問基本 class 的私有字段而不將它們公開(在其他語言中稱為“受保護”)。
考慮以下 class:
class Animal {
#privateProp;
constructor() {
this.#privateProp = 12;
}
}
現在擴展 class:
class Cat extends Animal {
constructor() {
super();
}
doIt() {
console.log(this.#privateProp) // 1 below
console.log(super.#privateProp) // 2 below
}
}
我想像受到保護一樣執行:
new Cat().doIt();
但是得到(分別):
- 未捕獲的語法錯誤:必須在封閉的 class 中聲明私有字段“#privateProp”
- 未捕獲的 SyntaxError:意外的私有字段
請注意,當 privateProp 公開時,此代碼將完美運行,但我想實現類似受保護的行為並像任何支持 inheritance 的語言一樣訪問“私有”字段。
任何幫助將不勝感激。
字段是私有的,類似於變量是塊作用域的; 如果某個屬性是某個class
的私有屬性,則只能在該 class 內部引用它。 如果您擴展 class,它將在派生的 class 中不可見。
如果您希望能夠從子類中使用它,您可以在超類上創建一個 getter/setter:
class Animal { #privateProp = 12; setProp(val) { this.#privateProp = val; } getProp() { return this.#privateProp; } } class Cat extends Animal { doIt() { console.log(this.getProp()); } } new Cat().doIt();
另一種方法是將“私有”字段定義為僅適用於 class 聲明的 WeakMap:
const { Animal, Cat } = (() => { const privateProps = new WeakMap(); class Animal { constructor() { privateProps.set(this, 12); } } class Cat extends Animal { doIt() { console.log(privateProps.get(this)); } } return { Animal, Cat }; })(); new Cat().doIt();
您可以通過檢查構造函數是否不是父 class 本身來創建具有訪問受限的 getter 和 setter 方法的私有屬性。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.