簡體   English   中英

js Inheritance 和私人會員

[英]Js Inheritance and private members

由於模糊的js實現細節,以下代碼崩潰。

class A {

  constructor(x) {
    this.X = x
  }

  get X()  { throw new Error('Child should know ...')}
  set X(x) { throw new Error('Child should know ...')}

}

class B 
  extends A {
  #X

  get X()  { return this.#X }
  set X(x) { this.#X = x }
}

const b = new B(3)
  set X(x) { this.#X = x }
                     ^

TypeError: Cannot write private member #X to an object whose class did not declare it
    at B.set X [as X] ([...]/Test.js:17:22)
    at new A ([...]/Test.js:4:12)
    at new B ([...]/Test.js:12:1)
    at Object.<anonymous> ([...]/Test.js:20:11)

有沒有辦法在不破壞 inheritance 邏輯的情況下在 class B 中保持 X 私有?

我希望有人能幫助我。 問候

Class B extends A {
 constructor(x) {
   super(x);
   this.X = x;
 }

 get X()  { return this.X }
 set X(x) { this.X = x }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM