By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – How to dynamically create a subclass from a given class and enhance/augment the subclass constructor’s prototype?
JavaScript

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

Admin
Last updated: 2024/02/10 at 1:48 PM
Admin
Share
5 Min Read
How to dynamically create a subclass from a given class and enhance/augment the subclass constructor's prototype?

Problem:

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:

Contents
Problem:Solution:
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”]

Solution:

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; }

Expand snippet

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Append values in a sizing chart Javascript – Append values in a sizing chart
Next Article How can I assign items to objects based on the allocation percentage of each object? Javascript – How can I assign items to objects based on the allocation percentage of each object?
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?