Im' trying to create a true abstract class in javascript where if you try to instantiate an abstract class, it throws an error. Problem is, when I do this, I can't create any default values in the abstract class. Here is my code:
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
This is happening because my get function is re-creating that object every time it is called. In a functino class, I would have used this.Num, but that doesn't compile in the class syntax. What should I do?