0
Im 'javascriptで真の抽象クラスを作成しようとしています。抽象クラスをインスタンス化しようとすると、エラーがスローされます。問題は、私がこれを行うとき、抽象クラスにデフォルト値を作成できないということです。私のコードは次のとおりです:JavascriptでTrue Abstractクラスを作成する
class Abstract {
constructor() {
if (new.target === Abstract) {
throw new TypeError("Cannot create an instance of an abstract class");
}
}
get Num() { return {a: 1, b: 2} }
get NumTimesTen() { return this.Num.a * 10 }
}
class Derived extends Abstract {
constructor() {
super();
}
}
//const a = new Abstract(); // new.target is Abstract, so it throws
const b = new Derived(); // new.target is Derived, so no error
alert(b.Num.a) // this return 1
b.Num.a = b.Num.a + 1
alert(b.Num.a) // this also returns 1, but should return 2
alert(b.NumTimesTen) // this returns 10, but should return 20
これは、get関数が呼び出されるたびにそのオブジェクトを再作成するためです。 Functinoクラスでは、私はthis.Numを使用していましたが、クラス構文ではコンパイルしません。私は何をすべきか?