Metaprogramming Classes in JavaScript
Sometimes when defining very similar objects, it can make sense to generate them all at once. For example here is how 3 classes of similar functions can be generated from an array and a single class definitions:
const classTypes = ['A', 'B', 'C']; for (let type of classTypes) { global[`class${type}`] = class { [`describe${type}`]() { return `A class of type ${type}`; }; } } const objA = new classA(); console.log(objA.describeA()); // A class of type A const objB = new classB(); console.log(objB.describeB()); // A class of type B const objC = new classC(); console.log(objC.describeC()); // A class of type C
global should be whatever the top level value (or object) that you want to attach the classes too. So window for browsers. In most cases, method names would remain the same across all classes, but I wanted to demonstrate that like everything else, those can have a unique name directly input.
I could not find a direct compatibility table of the support for those dynamic method names, only general support tables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions#Browser_compatibility). So instead I verified the above works manually with window in the latest Chrome, Firefox, Safari and MS Edge in addition to Node 10+ with global.
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/metaClass.js








