-1

I'm new to JavaScript and I'm trying to achieve the logic I have commented in the constructor method of the base class

export default class Building {
  constructor(sqft) {
    this._sqft = sqft;

    // when a subClass extends from this class
    // and does not implement `certainMethod()`, throw an error.
    // this should happen only when `subClass extends baseClass` and not with `new` keyword
    // object creation.
  }
}
2
  • What exactly do you mean by "this should happen only when subClass extends baseClass and not with new keyword object creation."? That the class SubBuilding extends Building {} statement itself throws the error? Or that new SubBuilding() call should throw the error, but instantiating new Building() should still be allowed? Commented Aug 3 at 10:09
  • @Bergi the first two lines of the comments is what i mean by this, new Building() should be allowed. subclassing with extends should throw an error when the subclass hasn't implemented the method in question. Commented Aug 3 at 10:51

1 Answer 1

1

You can check which concrete (subclass) constructor was invoked using new.target, and exempt the base class itself from the error condition:

export default class Building {
  constructor(sqft) {
    this._sqft = sqft;

    if (new.target != Building && typeof this.certainMethod != 'function') {
      throw new Error('…');
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.