Upon closer inspection, there is a fairly simple way for Node.js. When you instantiate an object in the simplest way, you actually write new <variableName> , where variableName is the body of some function or class defined and exported in some module. To assign this function / class to a variable, you require() it.
So instead
const type = 'Square'; const aSquare = new type();
you need to write:
const type = 'Square'; const shape = require(`${pathToShapeModules}/${type}.js`); const aShape = new shape();
A minor flaw is that eslint complains (in some rules) that require must be placed on top of the module. And, of course, for the correct handling of exceptions, an attempt is needed ... to catch, etc., Therefore, perhaps the Factory solution is better (therefore, I am going to take it), but I think that for small specialized cases this solution is in order.
Forseti
source share