vijayst vijayst - 9 months ago 67
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 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 Source

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