Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if class is child of class without instantiating

Say I have the following in a JavaScript module:

class A { ... }
class B extends A { ... }
class C extends B { ... }

How can I confirm that C is a descendant of A without creating an instance of C?

register(B);
register(C);

register(obj) {
  // I need this test, but without the new call
  if (!new obj() instanceof A) {
     throw Error "Not a child";
  }
  ...
}

Background: I'm trying to create a modular factory method that can automatically instantiate an object of the correct child type, without hard-coding the list. I'm doing this with a 'static register(obj)' method called from the module files that would be defining child classes. That allows the root application to import any required libraries without the module itself knowing what is available. As an extra sanity check, I want to ensure that the class is actually a descendant before adding it to the list.

like image 428
Digicrat Avatar asked Oct 15 '25 16:10

Digicrat


1 Answers

You don't need to instantiate, accessing the .prototype of the possible child will work:

class A {  }
class B extends A {  }
class C extends B {  }

console.log(C.prototype instanceof A)
like image 176
CertainPerformance Avatar answered Oct 18 '25 06:10

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!