0

I have a class name and want to use it to create a class instance dynamically. How can I do that?

class FieldText {
  constructor() {
    console.log('hello text field');
  }
}

class FieldTextarea {
  constructor() {
    console.log('hello textarea field');
  }
}

function callField(name) {
  new FieldText(); // Somehow use name variable instead to make it dynamic
  // new Field${name}(); // Does not work
}

callField('text');
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

1 Answers1

-1

class FieldText {
  constructor() {
    console.log('hello text field');
  }
}

class FieldTextarea {
  constructor() {
    console.log('hello textarea field');
  }
}

this.FieldText = FieldText;
this.FieldTextarea = FieldTextarea;

function callField(name) {
  return new this[`Field${name}`];
}

callField('Text');