2017-04-20 27 views
0

Im'試圖在JavaScript中創建一個真正的抽象類,如果你嘗試實例化一個抽象類,它會拋出一個錯誤。問題是,當我這樣做時,我無法在抽象類中創建任何默認值。這裏是我的代碼:用Javascript創建一個真正的抽象類

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