0
There is a way to instantiate a Javascript class whose name is contained in a string type variable?
For example:
class User {
constructor(...args) {
console.log(args);
}
}
const className = 'User';
const userInstance = new className();
// const userInstance = new User();
const name = userInstance.name;
console.log(name);
I would like the line:
const userInstance = new className();
Had the same effect as:
const userInstance = new User();
It is possible?
In the following link there are some ways to do, but they involve you having to rearrange your code in some way. See if any of them fit: https://stackoverflow.com/questions/34655616/create--instance-of-a-class-in-es6-with-a-dynamic-name/34656123
– Luís Henrique Faria
Neither. : s Needs to be a string. Possible?
– Luiz Felipe
So, from the forms presented in the link we are using string. Look at this example https://jsbin.com/qedura/edit?js,console
– Luís Henrique Faria
In the shown example the classes are defined in a constant object:
const classes = { Foo, Bar };
. That can’t happen. There’s another way?– Luiz Felipe
That’s why I said you have to tamper with the code and I didn’t put out an answer. I couldn’t think of any way to do it the way you want. There are probably better ways to solve your real problem, but we will need more information.
– Luís Henrique Faria
You could use Val, but they say it’s not safe(?):
const userInstance = eval('new '+className+'()');
– Sam