2017-04-20 2 views
0

Im '자바 스크립트에서 실제 추상 클래스를 만들려고합니다. 여기서 추상 클래스를 인스턴스화하려고하면 오류가 발생합니다. 문제는, 내가 이것을 할 때, 나는 추상 클래스에서 어떤 디폴트 값도 만들 수 없다는 것이다. 여기 내 코드는 다음과 같습니다.자바에서 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