skip to Main Content

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


  1. Chosen as BEST ANSWER

    Here's a solution (sorry about the switch to TypeScript):

    let operatorNames:Array<string> = ["add", "negate"];
    let root:object = new Calculator("someName");
    for (let operatorFunctionName of operatorNames) {
      switch (operatorFunctionName) {
        case "add":
          let addPrototype = class AddClass {
            add(left:number, right:number) {
              console.log(this.name + " " + (left + right));
            }
          };
          Object.setPrototypeOf(addPrototype.prototype, root);
          root = new addPrototype();
          break;
        case "negate":
          let negatePrototype = class NegateClass {
            negate(right:number) {
              console.log(this.name + " " + (-right));
            }
          };
          Object.setPrototypeOf(negatePrototype.prototype, root);
          root = new negatePrototype();
          break;
      }
    }
    return root as Calculator;
    

    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.


  2. 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.

    class Calculator {
      constructor() {
        this.name = "Calculator"
      }
    }
    
    // decorator to create a super calculator that can add
    const superCalculator = (calculator) => {
      const add = (a,b) => a+b
      return {...calculator, name: "Super Calculator", add};
    }
    
    const simpleCalc = new Calculator();
    const superCalc = superCalculator(simpleCalc);
    
    console.log(simpleCalc.name)
    console.log(superCalc.name)
    console.log(simpleCalc.add(3,4))  // simple calculator can not add 
    console.log(superCalc.add(3,4))   // super calculator can do it
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search