How to dynamically create a subclass from a given class and enhance/augment the subclass constructor's prototype?

301 views Asked by At

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"]

3

There are 3 answers

0
Peter Seliger On BEST ANSWER

One could choose a composition and inheritance based approach where a factory-function creates a named subclass/subtype on-the-fly.

As for the OP's use case, one in addition, applies function-based mixin-composition in order to augment the subclass constructor's prototype. Thus, everything is covered by inheritance (the prototype chain), either directly via the subclass constructor's augmented prototype or via the further linked prototype of the base class.

The advantage of the entire approach comes with not having to write too much boilerplate (and repeating) code if it comes to the dynamic (or add-hoc) creation of Calculator based subclasses.

// - factory function which implements dynamic sub-classing (or sub-typing).
// - the below implementation is generic, thus it not only allows/supports
//   the creation of named subclasses derived from the additionally provided
//   base class, but it also supports function-based mixin-composition at
//   both instance and class level.
function createNamedSubclassWithMixedInBehavior(
  className = 'UnnamedType' , baseClass = Object, mixinConfig = {}
) {
  const {
    compose: instanceLevelMixins = [],
    inherit: classLevelMixins = [],
  } = mixinConfig;

  const subClass = ({
    [className]: class extends baseClass {
      constructor(...args) {

        super(...args);

        instanceLevelMixins
          .forEach(behavior => behavior.call(this));
      }
    },
  })[className]; 

  classLevelMixins
    .forEach(behavior => behavior.call(subClass.prototype));

  return subClass;
}

// function-based mixins, each implementing a unique trait/behavior.
function withNegation() {
  this.negate = function negate (right) {
    return (-1 * right);
  }
}
function withAddition() {
  this.add = function add (left, right) {
    return (left + right);
  }
}
function withSubtraction() {
  this.subtract = function subtract (left, right) {
    return (left - right);
  }
}

// base `Calculator` class.
class Calculator {
  constructor(name) {
    this.name = name;
  }
}

// a lookup based configuration of operator mixins.
const operatorMixins = {
  negation: [withNegation],
  addition: [withAddition],
  subtraction: [withSubtraction],
  negation_addition: [withNegation, withAddition],
  negation_subtraction: [withNegation, withSubtraction],
  addition_subtraction: [withAddition, withSubtraction],
  negation_addition_subtraction: [withNegation, withAddition, withSubtraction],  
};

// helpers for calculator instance logs.
function getConstructorName(value) {
  return Object.getPrototypeOf(value).constructor.name;
}
function getBaseConstructorName(value) {
  return Object.getPrototypeOf(Object.getPrototypeOf(value)).constructor.name;
}

// creation, access and logging of `Calculator` subclasses.
[
  ['negation', 'NegationType', 'negationOnly'],
  ['addition', 'AdditionType', 'addOnly'],
  ['subtraction', 'SubtractionType', 'subtractOnly'],

  ['negation_addition', 'NegationAdditionType', 'negateAndAdd'],
  ['negation_subtraction', 'NegationSubtractionType', 'negateAndSubtract'],
  ['addition_subtraction', 'AdditionSubtractionType', 'addAndSubtract'],

  ['negation_addition_subtraction', 'NegationAdditionSubtractionType', 'negateAndAddAndSubtract'],
]
.map(([operatorFlag, className, instanceName]) => [
  createNamedSubclassWithMixedInBehavior(
    className, Calculator, { inherit: operatorMixins[operatorFlag] }
  ),
  instanceName,
])
.forEach(([CalculatorSubClass, instanceName]) => {

  const calculatorSubType = new CalculatorSubClass(instanceName);

  console.log({
    instanceName: calculatorSubType.name,
    className: getConstructorName(calculatorSubType),
    baseClassName: getBaseConstructorName(calculatorSubType),
    negate: calculatorSubType.negate,
    add: calculatorSubType.add,
    subtract: calculatorSubType.subtract,
    "negate(-7)": calculatorSubType?.negate?.(-7),
    "add(1,14)": calculatorSubType?.add?.(1, 14),
    "subtract(19,10)": calculatorSubType?.subtract?.(19, 10),
  });
});
.as-console-wrapper { min-height: 100%!important; top: 0; }

4
DoomGoober On

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.

EDIT: @Bergi suggests this is more elegant and solves the constructor problem I mentioned. Thank you @Bergi!

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

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. EDIT changed the code to use Object.Assign

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 Object.assign(calculator, {name: "Super Calculator", add})
}

const simpleCalc = new Calculator();
const superCalc = superCalculator(new Calculator());

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