Suppose I have the following JavaScript class code. (EDIT: the code is running as an ES6 module that is imported using the standard ES6 "import" statement. So the following class is in a standalone file "C.js")
export class C {
static f() {
console.log("hello world")
}
}
Now I want to import the module and invoke the method C.f(), but I only have the name of the method as a string. The following works fine:
import {C} from "C.js"
var methodName="f"
C[methodName]()
Now suppose that I also have the name of the class as a string as follows:
import {C} from "C.js"
var className="C"
var methodName="f"
/* How do I invoke C.f() ? */
Things I've tried:
- Using window/self/globalThis, which do NOT work:
import {C} from "C.js"
var className="C"
var methodName="f"
/* none of the below calls work */
window[className][methodName]()
self[className][methodName]()
globalThis[className][methodName]()
I've tried using the Function() constructor:
import {C} from "C.js"
var className="C"
var methodName="f"
/* the following does NOT work: */
var fn = new Function(className+"."+methodName+"()")
fn()
The above code gives an error that "C" is not defined, when the fn() is executed.
I've also tried using "eval()", which would be my last choice anyways since I don't really need to evaluate "arbitrary" code. I just want to execute a static method in a class, whose names are in strings.
import {C} from "C.js"
var className="C"
var methodName="f"
var code = className + "." + methodName + "()"
eval(code)
The above does NOT work in the Chrome web browser as part of a modern ES6 JavaScript application. The problem in the Chrome web browser is that the global "environment" used within "eval" does NOT see the "C" class definition.
So, what is the best way to implement this very simple call using string values for the class name and method name?
import {C} from "C.js"
var className="C"
var methodName="f"
/* now what? */