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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With