0

I try to setup an instance dynamically from a string. I've read many questions about it but the answers does not work for me.

It says it's possible to use window before the name to set the instance. It does not work.

class MyClass {
  // Something useful
}
let params = {};
let name = 'MyClass';
let instance = new window[name](params);

I've also tried to do this without luck (throws error):

let instance = new window['MyClass'](params);

However, this works:

let instance = new MyClass(params);

Why can't I use window in this case? Any other ideas?

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • 2
    You can only use `window` if it's a global variable. You must have defined the class in a local scope, not the global scope. – Barmar Jan 21 '19 at 09:41
  • @Barmar Yes, I'm in the constructor of another class. – Jens Törnell Jan 21 '19 at 09:43
  • 1
    A hacky way is to do `eval('var instance = new '+name+'()')`. The limitations look similar to an [older question of mine](https://stackoverflow.com/questions/49317114/determine-if-class-of-given-name-exists) – apokryfos Jan 21 '19 at 09:43

1 Answers1

2

Only global variables are put into window automatically.

Create an object that maps from class names to classes:

const classMap = {
    "MyClass": MyClass,
    "MyClass2": MyClass2,
    ...
};

Then use classMap[name](params) rather than window[name](params).

Barmar
  • 741,623
  • 53
  • 500
  • 612