1

JS6, Browser

How to create the instance of the class by its string name? For example I have a string Foo and I need to create an instance of Foo class. I don't want to write such construction:

let className = getClassName(); // returns 'Foo', `Stuff` or other
...
let item = null;

if(`Foo` == className){
  item = new Foo();
}
else if(`Stuff` == className){
  item = new Stuff();
}

UPD

I try to get access to my class constructor through the window object but I have the problem: it returns undefined. But my class exists and browser knows it:

enter image description here

Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182

2 Answers2

1

What you are trying to do is what you should do, in my opinion. This is a standard way of instantiating objects when the type of object is known at runtime, and is called the Factory Method Pattern.

You should avoid duplicating this everywhere in your code by using a factory object that will encapsulate the object creation. This factory object will have a method that will take the type name as its parameter.

Kapol
  • 6,383
  • 3
  • 21
  • 46
-1

Please use google: Instantiate a JavaScript Object Using a String to Define the Class Name

var myObject = window[classNameString];

P.S. I copy pasted your title of question and added javascript in front.

Ernestas Stankevičius
  • 2,420
  • 2
  • 24
  • 30