Good day. I had a question, how to create an object, having a class name in a variable? Is there a similar feature like the one implemented in php:

$className = 'MyClass'; $newObj = new $className(); 

Thank you in advance for your help.


On a tip, @Other did this:

  "use strict"; class Maxy { constructor() { this.Name = undefined; } Render() { console.log('Rendering...') } } let Maxies = { Mini1: class extends Maxy { }, Mini2: class extends Maxy { }, Mini3: class extends Maxy { } }; function CreateMini(Type) { let Mini = new Maxies[Type]; return Mini.Render(); } console.log(CreateMini('Mini2')); 

2 answers 2

Classes, like const and let , do not create properties in the global object, so finding them by name in a variable will not work.
Using eval can help, but everyone knows the rule: Don't use eval! .


You can create a property specifically (or jot down a simple plugin for Babel , which will do it yourself):

 window.Test = class Test{ notify(){ console.info('Yeah!'); } } let name = 'Test', app = new window[name]; app.notify(); 

But, honestly, I will not think of a situation where it is needed, because the Enum structures should be stored in a container:

 let np = { app: class{ notify(){ console.info('Yeah!'); } } }; let name = 'app', app = new np[name]; app.notify(); 

  • Thanks, @Other! I do not know what rake I will step on in the future, but so far I have realized my idea on the 2nd example. With eval () did not work, because it returns a function, not an object (well, or I somehow didn’t use it that way), and the window does not suit me, since I am writing code for the server side using node.js. - proudbird
  • @proudbird, please, thanks here are expressed by a plus and, if decided, by accepting an answer (check mark on the left). eval not for nothing that eval looks so much like evil :) window is a global object in the browser, global is an approximate equivalent for a node. - user207618

 class User { constructor(name) { this.name = name; } myName() { console.log(this.name); } } window.User = User; const a = 'User'; const b = new window[a]('Name'); b.myName(); 

  • Thanks for the help, @DimenSi, but I forgot to mention that I am writing for the server part, and there is no window object there. - proudbird
  • Global in node.js - DimenSi
  • Yes, it also worked through global, but through the array with classes I liked it more - at least I don’t need to add a bunch of additional properties with global, such as' global.class1 = class1; global.class2 = class2 ... ' - proudbird