Instantiate dynamic named class in Javascript

Asked

Viewed 271 times

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

  • Neither. : s Needs to be a string. Possible?

  • So, from the forms presented in the link we are using string. Look at this example https://jsbin.com/qedura/edit?js,console

  • In the shown example the classes are defined in a constant object: const classes = { Foo, Bar };. That can’t happen. There’s another way?

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

  • You could use Val, but they say it’s not safe(?): const userInstance = eval('new '+className+'()');

Show 1 more comment

1 answer

1


I do not see the need for this, your code will only have more lines, making it difficult to maintain the code.

Simple, use the function eval().

You can create a method to return a class instance.

const Classe = (name) => {
    let c = eval(name);
    return new c();
};

See working:

class User {
  constructor() {
    this._name = 'Luiz';
    this._age = 23;
  }

  get name() {
    return this._name;
  }
  get age() {
    return this._age;
  }
}

const Classe = (name) => {
  let c = eval(name);
  return new c();
};

const className = 'User';

const userInstance = Classe(className);
const name = userInstance.name;
console.log(name, userInstance.age);

Reference

  • Your answer gives error: Uncaught TypeError: Cannot read property 'name' of undefined

  • Truth I mosquei at the time of publishing had not paid attention.

  • Thank you, that’s right!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.