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?

3
  • 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. Commented Jan 21, 2019 at 9:41
  • @Barmar Yes, I'm in the constructor of another class. Commented Jan 21, 2019 at 9:43
  • 1
    A hacky way is to do eval('var instance = new '+name+'()'). The limitations look similar to an older question of mine Commented Jan 21, 2019 at 9:43

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.