2

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?

1 Answer 1

2

Figured it out. I can still put variable instantiating code in the abstract constructor.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.