vijayst vijayst - 1 month ago 11
Javascript Question

Dynamically calling a static method in a JavaScript / ES7 class

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.

Answer

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