I have an unusual situation where I need to dynamically generate a class prototype then have a reflection tool (which can’t be changed) walk the prototype and find all the methods. If I could hard code the methods, the class definition would look something like this:
class Calculator {
constructor(name) { this.name = name; }
}
class AdditionCalculator extends Calculator {
constructor(name) { super(name); }
add(left, right) { console.log(this.name + (left + right)); }
}
class SubtractCalculator extends AdditionCalculator {
constructor(name) { super(name); }
subtract(left, right) { console.log(this.name + (left - right)); }
}
However, I can’t hard code the methods/inheritance as I need a large number of combinations of methods that are data driven: For example, I need a Calculator with no math methods, a Calculator with Add() only, Calculator with Subtract() only, Calculator with Add() and Subtract(), and many more combos.
Is there any way to do this with JavaScript (I assume with prototypes)?
For reference, here’s the reflection tool that finds the methods:
function getMethods(obj:object, deep:number = Infinity):Array<string> {
let props:string[] = new Array<string>()
type keyType = keyof typeof obj
while (
(obj = Object.getPrototypeOf(obj)) && // walk-up the prototype chain
Object.getPrototypeOf(obj) && // not the the Object prototype methods (hasOwnProperty, etc...)
deep !== 0
) {
const propsAtCurrentDepth:string[] = Object.getOwnPropertyNames(obj)
.concat(Object.getOwnPropertySymbols(obj).map(s => s.toString()))
.sort()
.filter(
(p:string, i:number, arr:string[]) =>
typeof obj[<keyType>p] === 'function' && // only the methods
p !== 'constructor' && // not the constructor
(i == 0 || p !== arr[i - 1]) && // not overriding in this prototype
props.indexOf(p) === -1 // not overridden in a child
)
props = props.concat(propsAtCurrentDepth)
deep--
}
return props
}
For example: getMethods(new SubtractCalculator("name")); would return ["add", "subtract"]
2
Answers
Here's a solution (sorry about the switch to TypeScript):
We new up an instance of the base class, Calculator, which has no methods other than the constructor. Then we declare the derived class in local scope as a local variable (I tried doing it with global scope classes but then the classes were permanently changed.) Then, I set the local class prototype as having the instance of the base class as the prototype.
Then I instantiate the derived class and store that as the instance. Then repeat using the updated instance. In this way, I can dynamically keep adding derived classes on top of the derived classes.
Now, there's some hairiness here because the only way to call the Calculator constructor is manually before creating the derived class instance. I think I only have an instance of the derived class, not the derived class by itself (the derived class by itself couldn't be instantiated because the constructor for Calculator would not be called.) But that's OK, because all I needed was an instance of the derived class.
Calling getMethodNames(root) yields: ["add", "negate"] as expected.
You can use the
decorator
pattern to add functions to instances dynamically. It will be added officially to javascript hopefully, but you can use the fact that instances are objects to create a decorator pattern.