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.

3
  • do you need to create an instance of the class CustomClient ? Commented Oct 29, 2016 at 6:48
  • No, just call a static method on the class. Commented Oct 29, 2016 at 6:50
  • do you use modules? if so you probably need to import that class Commented Oct 29, 2016 at 6:51

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.