0

If I create the following classes, is there any way in Class1 to detect when the instance is actually one of Class2, without knowing anything about Class2?

i.e. Can Class1 tell when it's the parent class being extended?

class Class1 {
  constructor() {
    // Code to detect whether parent here
  }
}

class Class2 extends Class1 {
  constructor() {
    super();
  }
}
John Halbert
  • 1,320
  • 2
  • 12
  • 23

1 Answers1

6

This is what new.target was made for - it gives you the constructor that new was invoked with. So

class Class1 {
  constructor() {
    if (new.target != Class1) {
      // Class1 is used as a parent class
    }
  }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375