0

I have the className in a string variable. I want to call the addField static method on the dynamic class.

const className = "CustomClient"; // comes from dropdown.
CustomClient.addField();

CustomClient is the name of the ES7 class. addField is static method. I want to call the addField dynamically. The class can be one of CustomClient, CustomContract or CustomUser.

vijayst
  • 20,359
  • 18
  • 69
  • 113

1 Answers1

2

It's always the same when you want to reference a class by name - whether to instantiate it, to call a static method on it or something else: you have to build a name → class map and look it up:

const classes = {
    "CustomClient": CustomClient,
    …
}
var classRef = classes[className];

In your case, it would be

const classes = {CustomClient, CustomContract, CustomUser}; // shorthand notation
classes[className].addField();
Bergi
  • 630,263
  • 148
  • 957
  • 1,375