My goal is to have a base class and a subclass with class types that each have a static method identifying them using a string. This will enable me to easily look up handlers for different types in an object. I initially tried storing the class directly in the object, but converting the entire source of the class to a string and using that as a key did not seem like the most efficient solution.
Here are my requirements:
- Detect if a superclass is present
- Call `super.id()` then append my own `id()`
- If there is no super class, just use my own `id()`
I attempted to write the code in this way, but encountered issues because `super.id` is undefined. Checking for `if (super) {}` resulted in a syntax error, and calling `super.id()` returned "not a function".
class Y {
static id() {
if (super.id) {
return `${super.id()}-${this.name}`;
}
else {
return this.name;
}
}
}
class YY extends Y {}
// Currently outputs "Y YY", but desired output is "Y Y-YY"
console.log(Y.id(), YY.id())
I could define a `static id() {}` method in `YY`, but this would require manually implementing it in all subclasses, which can lead to errors. Is there a way to achieve this more efficiently?