Instantiate class with variable

0

There is a way to instantiate a class in JavaScript with a variable of type string , for example:

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

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

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();

It would have the same effect as:

const userInstance = new User();

Is it possible?

    
asked by anonymous 20.01.2018 / 15:23

1 answer

1
  

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

Simple, use the eval() function.

You can create a method to return an instance of the class.

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

21.01.2018 / 02:19