2017-04-20 11 views
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を使用していましたが、クラス構文ではコンパイルしません。私は何をすべきか?

答えて

0

抽象コンストラクタに変数をインスタンス化するコードを置くことができます。

class Abstract { 
    constructor() { 
    this.thing = {a: 1, b: 2} 
    if (new.target === Abstract) { 
     throw new TypeError("Cannot create an instance of an abstract class") 
    } 
    } 

    get Thing() { return this.thing } 
    get ThingATimesTen() { return this.thing.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.Thing.a) // this return 1 
b.Thing.a = b.Thing.a + 1 
alert(b.Thing.a) // now returns 2 
alert(b.ThingATimesTen) // now returns 20 
関連する問題